Python while循环使用或不提供已消耗的输出

时间:2015-07-02 11:27:25

标签: python while-loop logic

这是我的循环:

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,循环也会继续循环播放。

3 个答案:

答案 0 :(得分:5)

将条件更改为

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

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

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

答案 1 :(得分:3)

您需要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)')

答案 2 :(得分:3)

问题在于你的逻辑表达式:

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

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

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

显然,sure永远不能 'y''n',所以这不起作用。你想要的是:

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