对于代码中的“dog”部分,它工作得很好,并且做了它应该做的事情。但是,如果您在开始时输入“Cat”作为输入问题,它仍然继续执行代码的dog部分。在
即使我在代码中写过,如果问题的答案=“Cat”或“Cat”,那么它应该执行这个部分,而不是Dog部分。在
import time
import sys
animal=input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog")
if animal=="Dog"or"dog":
age=int(input("How old is your Dog?"))
if age==1:
print("Calculating the age of the Dog...")
time.sleep(1)
print("The age of the animal is: 11")
elif age==2:
print("Calculating the age of the Dog...")
time.sleep(1)
print("The age of the animal is: 11")
else:
age=age-2
print("Calculating the age of the Dog...")
time.sleep(1)
agecalculation=age*4+22
print("The age of the animal is:",agecalculation)
time.sleep(2)
print("End of program.")
time.sleep(2)
sys.exit()
elif animal=="Cat"or"cat":
age=int(input("How old is your Cat?"))
if age==1:
print("Calculating the age of the Cat...")
time.sleep(1)
print("The age of the animal is: 15")
elif age==2:
print("Calculating the age of the Cat...")
time.sleep(1)
print("The age of the animal is: 25")
else:
age=age-2
print("Calculating the age of the Cat...")
time.sleep(1)
agecalculation=age*4+25
print("The age of the animal is:",agecalculation)
time.sleep(2)
print("End of program.")
time.sleep(2)
sys.exit()
else:
print("That is not an animal, or isn't on the list specified")
animal=input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog")
您需要按如下方式编辑代码:
当您执行}。您可以使用
if animal == "Dog" or "dog"
时,它将计算ifanimal == "Dog"
,if{animal.lower() == "dog"
,或者使用上面编辑过的代码。在在python中,所有非空字符串都被计算为
true
,如下所示:将始终打印
True
因此,您需要设置if like:
^{pr2}$以下
if
测试的结果始终为true:上面的工作方式就好像有括号一样:
^{pr2}$在Python规则下,
or
的第二部分将始终求值为True:非空字符串的布尔值为True。在以下是三种可行的选择:
更多:这些问题可以在python方便的交互式命令提示符上轻松测试。例如,观察
"Dog"
和""
的布尔值:下面是合并声明:
相关问题 更多 >
编程相关推荐