字符串的Python while循环条件检查
在Codeacademy中,我运行了一个简单的python程序:字符串的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.
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
wherechoice!='是的,还是选择!='Y'
的计算结果为False?此外,它可能对您有用。