首页 > 解决方案 > 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()

标签: pythonpython-3.xuser-defined-functionsnameerror

解决方案


在函数play_game中,您有get_guess(num_guesses)返回变量guess 的行。但是,您没有将猜测值分配给函数中的变量。您可以通过将该行更改为guess = get_guess(num_guesses). 该错误会告诉您确切的问题。guess到目前为止,您还没有定义变量。


推荐阅读