【问题标题】:Getting warning: Name 'guess' can be undefined收到警告:名称“猜测”可能未定义
【发布时间】:2021-12-15 09:10:32
【问题描述】:

我在最后一个 if 语句中收到最后一个 guess 的警告。我可以忽略这一点并确定我的程序不会出现错误吗?

import random
print('Try to guess hidden number from 1 to 50, U have 6 tries by the way')
hidden_num = random.randint(1, 50)
tries = 6
while tries>0:
    guess = int(input(f'Guess the hidden number, tries left: {tries}\n'))
    tries-=1
    if guess == hidden_num:
        print('Great Job, You got it!')
        break
    elif guess < hidden_num:
        print('U were so close, take a bit higher')
    else:
        print('WowWo! Pick lower,Dude!')
if guess != hidden_num and tries == 0:
    print('Don\'t be upset buddy, you have whole life ahead!')

【问题讨论】:

  • 据我所知,这是 linter 中的误报。
  • 有什么问题??我执行了你的代码,效果很好
  • 我正在使用 Pycharm,它工作正常,但它给了我关于最后一个 guess @AbhijitShirwal 的警告
  • @nima 它在标题中:名字'guess'可以是未定义的
  • 警告是正确的,如果您将最后一条语句留在“while”循环之外,则该行的“guess”可能未定义。 'guess' 是在循环内部定义的,循环有可能不会执行,所以 'guess' 是未定义的。它只是提醒您检查这是否是想要的愿望。

标签: python-3.x loops random


【解决方案1】:

解决了警告问题,只是通过tab最后一个if条件,但仍然不明白这两种情况之间的代码执行差异是什么:

    if guess != hidden_num and tries == 0:
        print('Don\'t be upset buddy, you have whole life ahead!')

和:

if guess != hidden_num and tries == 0:
    print('Don\'t be upset buddy, you have whole life ahead!')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2011-09-28
    • 2023-03-16
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多