繁体   English   中英

Python while循环条件检查字符串

[英]Python while loop condition check for string

在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: ")

这似乎可行。 不知道为什么

你的逻辑倒过来了。 使用and代替:

while choice != 'y' and choice != 'Y' and choice != 'N' and choice != 'n':

通过使用or ,输入Y表示choice != 'y'为真,因此其他or选项不再重要。 or表示其中一个选项必须为true,并且对于任何给定的choice值,总是有至少一个!=测试是真实的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM