字符串的Python while循环条件检查

字符串的Python while循环条件检查,python,while-loop,Python,While Loop,在Codeacademy中,我运行了一个简单的python程序: choice = raw_input('Enjoying the course? (y/n)') while choice != 'y' or choice != 'Y' or choice != 'N' or choice != 'n': # Fill in the condition (before the colon) choice = raw_input("Sorry, I didn't catch that.

在Codeacademy中,我运行了一个简单的python程序:

choice = raw_input('Enjoying the course? (y/n)')

while choice != 'y' or choice != 'Y' or choice != 'N' or choice != 'n':  # Fill in the condition (before the colon)
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")
我在控制台输入y,但循环从未退出

所以我用了另一种方式

choice = raw_input('Enjoying the course? (y/n)')

while True:  # Fill in the condition (before the colon)
    if choice == 'y' or choice == 'Y' or choice == 'N' or choice == 'n':
        break
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")

这似乎奏效了。不知道为什么你的逻辑颠倒了。改用

while choice != 'y' and choice != 'Y' and choice != 'N' and choice != 'n':
通过使用
,键入
Y
意味着
选择!='y'
为真,因此其他
选项不再重要
表示其中一个选项必须为真,并且对于
选项的任何给定值
,始终至少存在一个
=将要成为真的测试

通过使用
choice.lower()
并仅针对
y
n
进行测试,然后使用成员资格测试,您可以节省一些键入工作:

while choice.lower() not in {'n', 'y'}:

提示:您能说出
choice
where
choice!='是的,还是选择!='Y'
的计算结果为False?此外,它可能对您有用。