【问题标题】:While statement and boolean OR in PythonPython中的while语句和布尔OR
【发布时间】:2018-02-24 05:44:51
【问题描述】:
y=''
print 'y= nothing'
y = raw_input('-->')
while y!='O' or y!='X':
    print 'You have to choose either X or O'
    y = raw_input('-->')
print 'Loop exited'
print y

谁能解释一下为什么上面的代码在python中不能正常运行?

我假设任何时候用户输入除“X”或“O”以外的内容时,他都会收到消息和输入提示。但只要用户提供“X”或“O”,循环就应该退出。但它没有......你们能帮忙吗?我是python新手...

【问题讨论】:

  • 在你的 while 循环中使用 and 而不是 or
  • 你的条件和not (y=='O' and y=='X')一样,y不能等于两个不同的字符。所以y=='O' and y=='X'总是False,然后not (y=='O' and y=='X')总是True。我想你想要的是y!='O' and y!='X'
  • @Serjik 逻辑与作者想要的不一样。我认为当y 等于'O''X' 时,OP 想要进入循环。
  • @Jerrybibo 没错,你明白了!)))对不起,如果我的解释不是那么清楚。如果 Y = X 或 Y = O,我不想进入循环。

标签: python while-loop boolean


【解决方案1】:

对这个错误的逻辑流程有几个修复。 @Aanchal Sharma 已经提到了一个,在 while 循环中有两个 != 和一个 and,如下所示:

while y != 'O' and y != 'X':

另一种解决方案是使用in,我个人认为它更具可读性:

while y not in ['X', 'O']:
    print 'You have to choose either X or O'
    y = raw_input('--> ')

希望这有帮助!

【讨论】:

    【解决方案2】:

    另一种方法是使用while Truebreak 语句:

    while True:
        y = raw_input('-->')
    
        if  y in ['O', 'X']:
            break
        print 'You have to choose either X or O'
    
    print 'Loop exited'
    print y
    

    例如:

    -->a
    You have to choose either X or O
    -->b
    You have to choose either X or O
    -->c
    You have to choose either X or O
    -->O
    Loop exited
    O
    

    这避免了需要有两个输入语句。

    【讨论】:

    • 谢谢)我是瞎写的)你100%正确)
    【解决方案3】:
    y=''
    print 'y= nothing'
    y = raw_input('-->')
    while (y!='O' and y!='X'):
        print 'You have to choose either X or O'
        y = raw_input('-->')
    print 'Loop exited'
    print y
    

    使用“和”条件而不是“或”。在您的情况下,y 将始终不等于“O”或不等于“X”。不能同时等于两者。

    【讨论】:

    • 如果y 是'O',那么循环应该退出,因为它说'你必须选择X 或O'。循环应该只持续到y 不是“X”或“O”。
    • @anuragal 我认为你误解了作者想要什么。
    • @AanchalSharma 谢谢。你说的对。在我的错误文章中,我总是有 Y !=1 或 Y !=2 :) 这很有趣。说什么....新手:) 感谢您的帮助。
    猜你喜欢
    • 2017-11-10
    • 2014-09-12
    • 2016-05-17
    • 1970-01-01
    • 2020-06-17
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多