While循环条件中的变量应退出循环,但不退出

时间:2018-11-08 16:09:43

标签: python python-3.x

我不知道为什么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) : ")

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您的if语句必须是and而不是or。尽管我建议使用not inlist并检查到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