python - Python "Else" 语句总是返回 True
问题描述
print("Hello World")
print("How're you?")
mood = input()
print("I'm " + mood + " too")
print("What's your name?")
name = input()
print(name + ". I really like that name!")
food = input("I really like pizza. Do you? Y/N ")
if food == 'y' or 'Y':
print("Wow! " + name + ", you and I have a really similar taste in food, don't we? So what else do you like?")
elif food == 'n' or 'N':
print("Oh, that's a shame. I was gonna treat us to a cheeky Papa Johns!")
else:
print("Oh! Okay. Then what else do you like?")
other = input()
if other == 'liquorice' or 'Liquorice' or 'Brussels Sprouts' or 'brussels sprouts':
print("Blegh! " + name + ", I respect you and all... but gross!")
当我输入 Y 或 y 以外的内容(代表是)时,我试图让程序使用 ELIF 和 ELSE 输出。我需要做什么来修复这个错误?
解决方案
当你使用
if food =='y' or 'Y':
python会一直返回true,你可以测试一下:
if 'false':
print('true')
要使其正常工作,请替换food =='y' or 'Y'
为food =='y' or food=='Y'
或者按照@Peter Wood 的建议,使用food