我不知道为什么while循环无法正常工作。
bday = input("Has your birthday already passed? (y|n) : ")
print(bday)
while True:
if (bday != 'y' or bday != 'Y' or bday != 'n' or bday != 'N'):
print("Invalid input, please enter Y or N.")
print(bday)
bday = input("Has your birthday already passed? (y|n) : ")
else:
break
根据我的打印报表,我的“ bday”值正确地视为“ y”,“ Y”,“ n”或“ N”。但是,由于某种原因,条件的作用好像是错误的值。
原始编码为:
while (bday != 'y' or bday != 'Y' or bday != 'n' or bday != 'N'):
print("Invalid input, please enter Y or N.")
print(bday)
bday = input("Has your birthday already passed? (y|n) : ")
感谢您的帮助。
答案 0 :(得分:3)
您的if
语句必须是and
而不是or
。尽管我建议使用not in
和list
并检查到bday.lower()
:
bday = input("Has your birthday already passed? (y|n) : ")
print(bday)
while True:
if bday.lower() not in ['y', 'n']:
print("Invalid input, please enter Y or N.")
print(bday)
bday = input("Has your birthday already passed? (y|n) : ")
else:
break
答案 1 :(得分:1)
逻辑上有错误。如果要让程序再次询问用户输入的内容是否不是(“ y”或“ Y”或“ n”或“ N”),则必须使用“ and”而不是“ or”
尝试:
while True:
bday = input("Has your birthday already passed? (y|n) : ")
if ((bday != 'y') and (bday != 'Y') and (bday != 'n') and (bday != 'Y')):
print("Invalid input, please enter Y or N.")
else:
break