如何解决函数从文本文件中读取单词但返回 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)
解决方法
你需要像这样递归调用后返回,
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()
,
您得到“无”,因为您在结尾使用了 print
语句。您应该只输入变量名称,即 random_seven_letter_word()
。你甚至应该把2个括号。所以最终的代码将是 -
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,type(word))
return word
else:
return find_word()
random_seven_letter_word = find_word()
random_seven_letter_word()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。