在 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()
并仅针对 y
和 n
进行测试,然后使用成员资格来节省一些打字工作测试:
while choice.lower() not in {'n', 'y'}:
关于Python while 循环条件检查字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31565609/