【问题标题】:Dog Age Calculator Python Undefined Name Error狗年龄计算器 Python 未定义名称错误
【发布时间】:2021-10-13 16:41:28
【问题描述】:

我正在尝试创建一个程序,当输入狗的年龄时,它会计算出人类的年龄。如果输入负数,则应打印负数无效。此外,如果输入不是数字,它应该打印输入无效。我的代码在我的编辑器中运行,但是在 jupyter 笔记本中它挂在 dog_age 未定义上。我不知道变量“a”是否也会有同样的问题。

dog_age = input("How old is your dog in years?")

try:
    d_a = float(dog_age)

    if d_a < 0:
        print(" Your input can not be negative! ")
    if (d_a >= 0) & (d_a <= 1):
        a = d_a * 15
    if d_a == 1:
        a = 15
    if (d_a > 1) & (d_a > 2):
        a = (d_a * 12)
    if d_a == 2:
        a = 24
    if (d_a > 2) & (d_a < 3):
        a = (d_a * 9.3)
    if d_a == 3:
        a = 27
    if (d_a > 3) & (d_a < 4):
        a = (d_a * 8)
    if d_a == 4:
        a = 32
    if (d_a > 4) & (d_a < 5):
        a = (d_a * 7.2)
    if d_a >= 5:
        a = (d_a * 7)
except ValueError as e:
    print("Your input was not valid")

round(a, 2)
a = str(a)

print("You inputted your dogs age as " + dog_age + " that is equal to " + a + " Human years old")

【问题讨论】:

  • 欢迎来到 Stack Overflow!请始终发布带有完整追溯整个错误消息
  • 你没有对round(a, 2) 的结果做任何事情。它不会就地修改变量,而是返回四舍五入的值。所以应该是a = round(a, 2)
  • 我不明白这段代码的复杂性。不就是人类年 = 7 x 狗年吗?
  • 响应输入提示后,dog_age 没有理由不被定义。

标签: python function nameerror undefined-variable


【解决方案1】:

如果您输入的年龄介于 1 和 2 之间,a 将没有任何值:

if (d_a > 1) & (d_a > 2):
        a = (d_a * 12)

除了if d_a == 1:已经被前面的语句覆盖了。

最后正如 Sujay 指出的,Python 中的逻辑运算符是and&amp; 是按位运算符,在您的情况下是不必要的。

【讨论】:

  • and 而不是&amp;?
猜你喜欢
  • 2012-03-26
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2020-12-28
相关资源
最近更新 更多