Python while 循环有或没有给出预期的输出

Python while loop with or not giving expeted output

这是我的循环:

sure = input('Are you sure that you wish to reset the program?(y/n)')
while sure != 'y' or sure != 'n':
    sure = input('Please awnser y or n, Are you sure that you wish to reset the program?(y/n)')

即使输入yn循环也会继续循环

将条件更改为

while sure != 'y' and sure != 'n':

无论他们输入什么,您所写的条件总是 True。另一种选择是

while sure not in ('y','n'):

您需要执行 and 而不是 or 。在执行 or 时,如果肯定不是 y 以及 n ,它将继续循环,但肯定不能同时是两者,因此它会永远循环。

例子-

sure = input('Are you sure that you wish to reset the program?(y/n)')
while sure != 'y' and sure != 'n':
    sure = input('Please awnser y or n, Are you sure that you wish to reset the program?(y/n)')

问题出在你的逻辑表达式中:

sure != 'y' or sure != 'n'

使用德摩根定律,这可以改写为:

!(sure == 'y' and sure == 'n')

显然,sure 永远不可能是 'y''n',所以这是行不通的。你想要的是:

sure != 'y' and sure != 'n'