Python 3.x中的“未使用本地变量'name_variable'值”错误

时间:2018-08-13 10:57:28

标签: python python-3.x

因此,我是编程新手,目前正在学习Python。 在尝试制作简单游戏时,尝试将变量user_answer更改为input("Please, answer with yes or no.")时遇到了麻烦。 基本上,这是我的代码行else: user_answer = input("Please, answer with yes or no.")。 但是由于某种原因,我收到一个错误,称为“未使用本地变量'user_answer'值”。 有人可以帮我吗? 预先感谢!

这是我的完整代码:

def my_function():
    user_answer = input("Would you like to play a game?")
    if user_answer == "yes":
        print("Great! I have a number in my head from 1 to 10. Make a guess!")
    elif user_answer == "no":
        print("Oh, okay! Maybe next time?")
    else: user_answer = input("Please, answer with yes or no.")


my_function()

2 个答案:

答案 0 :(得分:2)

我猜您是在谈论IDE检查,而不是实际的运行时错误?您是否正在使用像PyCharm这样的IDE?如果是这样,local variable ... value not used意味着您正在将值(input(...))存储在变量(user_amswer)中,那么您就永远不会使用该值。但这确实是应该的,因为看来您的程序到此结束了。没有任何东西正在使用user_answer的新值。

只需忽略警告,继续编写程序(并确保使用新的user_answer值),就没有问题了。



工作示例

def my_function():
    user_answer = input("Would you like to play a game? ")

    while not (user_answer == "yes" or user_answer == "no"):
        user_answer = input("Please, answer with yes or no. ")

    if user_answer == "yes":
        print("Great! I have a number in my head from 1 to 10. Make a guess!")
    elif user_answer == "no":
        print("Oh, okay! Maybe next time? ")


my_function()

在此示例中,我们首先使用user_answer = input("Would you like to play a game? ")获取用户输入,然后确保循环中的输入是“是”或“否”

while not (user_answer == "yes" or user_answer == "no"):
        user_answer = input("Please, answer with yes or no. ")

仅当(user_answer == "yes" or user_answer == "no")的值为True时终止。

然后您可以继续执行该程序的其余部分!

# if user_input...


为什么不起作用

使用您先前的代码,在用户未输入有效答案(elseyes)时执行no语句。但是问题是,一旦用户输入了一个新值(该值也可能是无效的!),该程序就无处可去了(它已经“遗忘”了if user_answer == "yes": print(...)代码!)。

答案 1 :(得分:0)

谢谢大家!我正在使用PyCharm IDE,问题是该变量在我的程序中没有任何用处。我可以继续编写程序,结果是:

import random

user_name = input("Welcome to the number guessing game! What's you name?")

random_number = random.randint(1, 10)
user_guess = int(input("Okay " + user_name + ", I have a random number in my head from 1 to 10, make a guess!"))
while user_guess != random_number:
    if user_guess > random_number:
        user_guess = int(input("You're too high, try lower!"))
    elif user_guess < random_number:
        user_guess = int(input("You're too low, try higher!"))
    elif user_guess == random_number:
        break

print("You're correct! The number is " + str(random_number) + "!")

感谢大家的帮助! 干杯:)