首页 > 解决方案 > 函数从文本文件中读取单词但返回 None

问题描述

我在 Python3 中编写了这段代码,我认为它会从包含一长串单词的文本文件中返回一个随机的七个字母单词(用于猜词游戏)。它确实找到了这样一个词,但返回 None。谁能解释为什么?

from random import randrange
import os

def find_word():
        f = open('dictionary.txt')
        lines = f.readlines()
        x = randrange(1000)
        word = lines[x]
        word = word.rstrip(os.linesep)
        # removes the new line part of text, but the problem is the same with 
        # or without this line
        if len(word) == 7:
            print(word, type(word))
            return word
        else:
            find_word()
    
random_seven_letter_word = find_word()
print(random_seven_letter_word)

标签: pythonnonetype

解决方案


您需要在这样的递归调用之后返回,

def find_word():
        f = open('dictionary.txt')
        lines = f.readlines()
        x = randrange(1000)
        word = lines[x]
        word = word.rstrip(os.linesep)
        # removes the new line part of text, but the problem is the same with 
        # or without this line
        if len(word) == 7:
            print(word, type(word))
            return word
        else:
            return find_word()

推荐阅读