Python while 循环条件检查字符串

标签 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. 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':

通过使用 or,输入 Y 表示 choice != 'y' 为真,所以另一个 or 选项不再重要。 or 意味着 一个 选项必须为真,并且对于 choice 的任何给定值,总有至少一个你的 != 测试是否为真。

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

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

关于Python while 循环条件检查字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31565609/

相关文章:

php - 想要一个 while 循环仅在表中显示数据库中的商店列表

java - 返回随机字母的迭代器无法让它迭代

python - 在python中评估if的条件

java - 将嵌套 for 循环编写为 while

python - plotly : How to annotate multiple lines in Plotly Express?

python - 如何在没有for循环的情况下通过多个索引获取/设置numpy矩阵中的元素?

c - 在 C 中不中断地退出 while 循环

javascript - 从 AJAX 请求返回 while 循环

Python:某些 pygame 对象不出现

python - OpenCV 重映射插值错误?