我正在尝试创建一个程序,当输入狗的年龄时,它将计算出人类的年龄。如果输入一个负数,它应该打印出这个负数是无效的。此外,如果输入不是一个数字,它应该打印输入无效。我的代码在我的编辑器中运行,但是在jupyter笔记本中它挂在未定义的dog_age上。我不知道变量是否也会有同样的问题
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")
如果输入的年龄在1到2之间,则a没有任何值:
if (d_a > 1) & (d_a > 2):
a = (d_a * 12)
此外,if d_a == 1:
已经在前面的语句中包含了。
最后,正如Sujay指出的,Python中的逻辑运算符是and
。&
是一个位运算符,在你的例子中是不必要的。