對於代碼中的「狗」部分,它完美地工作並完成它應有的功能。但是,如果在開始時爲輸入問題輸入「Cat」,它仍會繼續並執行代碼的狗部分。使用if/elif語句遇到問題
即使我在代碼中寫道,如果問題==「貓」或「貓」的答案,那麼它應該做這個部分而不是狗部分。
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")
請使用一致的縮進(每個級別總是4個空格)。這在Python中具有語義相關性。 – Nabla
'如果動物==「狗」或動物==「狗」:'但也許你應該寫'如果animal.lower()==「狗」:' – pasztorpisti
感謝您的快速回復pasztorpisti - 第一部分解決了它完美。榮譽給你。 – user3376281