【问题标题】:Python while loop with or not giving expeted outputPython while 循环有或没有给出预期的输出
【发布时间】:2015-07-02 11:27:24
【问题描述】:

这是我的循环:

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

【问题讨论】:

    标签: python while-loop logic


    【解决方案1】:

    将条件改为

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

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

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

    【讨论】:

    • 谢谢,我使用了 not in 建议
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 1970-01-01
        • 2018-09-18
        • 2019-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多