python - 函数从文本文件中读取单词但返回 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()
推荐阅读
- php - 如何使用 php 从 mysql 获取当前的 user_id?
- python - 重命名不同列中的值后,pandas DataFrame 浮点列被转换为对象
- python - 我如何检测触摸何时在kivy的儿童小部件中
- amazon-web-services - Autoscaling Spot 队列无法向负载均衡器注册实例
- php - 雄辩的查询,检查电子邮件集合上的集合,以查找批准每封电子邮件的批准者,但并非所有人都具有approval_status
- sql - Postgres 索引在删除表上损坏
- c# - “无法执行脚本,因为脚本入口点无效”SSIS 中脚本任务中的错误
- python-3.x - DynamoDB 扫描未返回所需的输出
- java - 无法从 Naukri 网站的悬停菜单中单击选项
- vba - 我是否不正确地使用了 Columns() 属性,如果是,是否有一个好的解决方法?