【问题标题】:"Local variable 'name_variable' value is not used" error in Python 3.xPython 3.x 中的“未使用局部变量 'name_variable' 值”错误
【发布时间】:2018-08-13 10:57:27
【问题描述】:

所以,我是编程新手,目前正在学习 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()

【问题讨论】:

  • 这不是 Python 错误,可能只是来自 IDE 的警告。这可能是因为您在此之后不再使用user_answer
  • 请注明您使用的是哪个IDE。

标签: python python-3.x


【解决方案1】:

我猜你说的是 IDE 检查,而不是实际的运行时错误?你在使用像 PyCharm 这样的 IDE 吗?如果是这样,local variable ... value not used 意味着您将一个值 (input(...)) 存储在一个变量 (user_answer) 中,然后您永远不会使用该值。但这就是应该的,因为您的程序似乎到此为止;没有使用 user_answer 的新值。

忽略警告并继续编写程序,确保使用变量的新值,警告就会消失。

就上下文而言,此警告的目的是及早发现编程错误。假设我想写一个函数,它接受一个列表并将中间的元素附加到两端(前后),我写了这个:

def wrap_with_middle_element(sequence):
    mid = sequence[len(sequence)//2]
    sequence.append(element)
    sequence.insert(0, element)
    return sequence

您会注意到,在定义变量mid 之后,我实际上并没有使用它,而是使用了element。这可能是因为,例如,有一个名为 element 的全局变量,IDE 建议它作为代码完成并且我心不在焉地接受了,或者因为 mid 以前被命名为 element,并且手动将其重命名为 mid (而不是使用 IDE 的功能),我忘记重命名变量的其他两个外观。 (我知道这似乎不太可能,但这只是为了说明。)在这种情况下,IDE 将显示警告:Local variable 'mid': value is not used,因为我定义了mid,但从不使用它。我会很快意识到出了什么问题并修复它(而不是稍后在运行程序时发现)。



OP 代码的工作示例

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

    while user answer not in ('yes', '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 user_answer not in ('yes', 'no'):
        user_answer = input("Please, answer with yes or no. ")

仅当 user_answer in ('yes', 'no')(或等效的 user_answer == 'yes' or user_answer == 'no')计算为 True 时才会终止。

然后你可以继续程序的其余部分!

# if user_input...

为什么它不起作用

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

【讨论】:

  • 感谢您的回答,但问题是我希望程序在答案变为“是”或“否”时打印,这就是为什么我要更改 user_answer 的输入
  • @Manu 如果我错了,请纠正我;对于最后一个else 语句,您希望程序确保用户输入"yes""no",而不是"foo" 之类的其他内容?
  • 老兄,你救了我的命!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
相关资源
最近更新 更多