python - builtins.NameError:名称“猜测”未定义
问题描述
我正在做一个实验室任务,几天来我一直在努力解决一个错误。我在我的函数中也编写了 return ,它一直说有 aNameError:
而我没有定义它。
这是我正在处理的代码,因为我还没有完成,所以一切都搞砸了。但我很想知道我搞砸了什么以及如何解决名称错误。谢谢!
import random
def main():
instructions = display_instructions("instructions.txt")
#display instructions
display_instructions(instructions)
list_of_words = ['apple', 'banana', 'watermelon', 'kiwi', 'pineapple',
'mango']
correct_word=random.choice(list_of_words)
answer = list(correct_word)
puzzle = []
puzzle.extend(answer)
display_puzzle_string(puzzle)
play_game(puzzle, answer)
display_result(is_win, answer)
input('Press enter to end the game.')
def display_instructions(filename):
instruction_file=open("instructions.txt","r")
file_contents=instruction_file.read()
instruction_file.close()
print(file_contents)
def display_puzzle_string(puzzle):
for i in range(len(puzzle)):
puzzle[i] = '_'
print('The answer so far is '+" ".join(puzzle))
def play_game(puzzle, answer):
num_guesses = 4
while num_guesses > 0:
get_guess(num_guesses)
update_puzzle_string(puzzle, answer, guess)
display_puzzle_string(puzzle)
is_word_found(puzzle)
def get_guess(num_guesses):
guess=input('Guess a letter '+'('+str(num_guesses)+' guesses remaining):')
return guess
def update_puzzle_string(puzzle, answer, guess):
for i in range(len(answer)):
if guess.lower() == answer[i]:
puzzle[i] = guess.lower()
num_guesses += 1
return puzzle
def is_word_found(puzzle):
if puzzle == answer:
return is_win
def display_result(is_win, answer):
if is_win:
print('Good job! You found the word '+correct_word+'!')
else:
print('Not quite, the correct word was '+correct_word+
'. Better luck next time')
main()
解决方案
在函数play_game
中,您有get_guess(num_guesses)
返回变量guess 的行。但是,您没有将猜测值分配给函数中的变量。您可以通过将该行更改为guess = get_guess(num_guesses)
. 该错误会告诉您确切的问题。guess
到目前为止,您还没有定义变量。
推荐阅读
- c# - 在不从调用 NLog 的项目中引用 NLog.Web 的情况下让 {aspnet-request} 正常工作
- google-sheets - 通过 VLOOKUP 翻译 Google 表格查询操作的每个结果行
- shopify - Shopify Liquid - 您可以在产品页面上获取特定页面的元字段吗?
- r - 使用 ggplot2 geom_point() 绘制二进制(存在/不存在)数据
- css - 是否可以创建一个仅通过单击打开和关闭并在鼠标离开时关闭的纯 CSS 菜单?
- python - 我想将 TextInput 转换为 int var
- php - 在 Yocto 中启用 php intl 扩展
- anypoint-studio - 如何在 anypoint studio 中显示 RAML 文件中的特定记录?
- ssl - Lets Encrypt 的 SSL 不适用于 www 子域
- algorithm - 如何使用 trie(或后缀 trie)生成所有回文子串?