只是学习如何编码,并希望制作一个小程序来查看我所知道的内容。
n = int(input("Pick a number any Number: "))
if n > 100:
print ("No... Not that Number")
else:
answer = input("Would you like to know your number?")
if answer == "Y" or "Yes" or "y" or "yes":
print ("Your number is %s" % (n))
elif answer == "N" or "No" or "n" or "no" or "NO":
print ("Oh, well that's a shame then.")
else:
print ("Please type Yes or No")
input("Press Enter/Return to Exit")
一切正常,但第二个if
语句除外,它不会跟随输入input
的任何数据。这样做的原因是什么?
答案 0 :(得分:1)
Python不是人类,它不理解
if answer == "Y" or "Yes"
你的意思。你应该做
if answer == 'Y' or answer == 'Yes'
甚至更好
if answer in ('Yes', 'Y', 'yes', 'y')
甚至更短
if answer.lower() in ('yes', 'y')
答案 1 :(得分:0)
==
的优先级高于or
。因此,在if
条件下,您要检查answer == 'Y'
然后or
使用"Yes"
这个布尔表达式,这是一个非None
字符串,所以评估为True
。相反,您应该使用in
运算符来检查answer
是否是您感兴趣的值之一:
if answer in ("Y", "Yes", "y", "yes"):
print ("Your number is %s" % (n))
elif answer in ("N", "No", "n", "no", "NO"):
print ("Oh, well that's a shame then.")
else:
print ("Please type Yes or No")