首页 > 解决方案 > 如何使 TypeError:'NoneType' 类型的对象没有 len() 与刽子手游戏消失

问题描述

import random

hangmanGame = True
while hangmanGame:
    def wordsPickedBank():
        with open('words.txt', 'r') as file:
            allText = file.read()
            words = list(map(str, allText.split()))
            wordsPickedBank(random.choice(words))

    wordPicked = wordsPickedBank()
    word_length = len(wordPicked)
    guesses = str.split("")

** 第 14 行出现错误,您能帮忙完成这项工作吗?我正在尝试使单词显示为“_”,并从文本文件中随机选择单词。你能展示如何解决这个问题,以便循环继续而不向用户显示单词吗?**

标签: pythonwhile-loop

解决方案


按如下方式编辑您的函数:

while hangmanGame:
    def wordsPickedBank():
        with open('words.txt', 'r') as file:
            allText = file.read()
            words = list(map(str, allText.split()))
            return random.choice(words)

要返回一个变量,你必须使用return关键字,而不是函数本身。


推荐阅读