Python while循环条件检查字符串

2024-09-27 09:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在codecademy中,我运行了一个简单的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: ")

这似乎很管用。不知道为什么


Tags: ortheininputrawconditionfillchoice
1条回答
网友
1楼 · 发布于 2024-09-27 09:27:05

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

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

通过使用or,输入Y意味着choice != 'y'是真的,所以其他or选项不再重要。or意味着选项中的一个必须为true,并且对于任何给定的choice值,始终至少有一个!=测试将为true。

您可以通过使用choice.lower()来节省一些输入工作,只对yn进行测试,然后使用成员资格测试:

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

相关问题 更多 >

    热门问题