【问题标题】:while loop with or condition带有或条件的while循环
【发布时间】:2018-06-11 12:12:14
【问题描述】:

在第二个 while 循环中,我被卡住了,永远无法摆脱。如何解决?

def playGame(wordList):

new_hand = {}

choice = input('Enter n to deal a new hand, or e to end game: ')   
while choice != 'e':
    if choice == 'n':
        player_or_pc = input('Enter u to have yourself play, c to have the computer play: ')
        while player_or_pc != 'u' or player_or_pc != 'c':
            print('Invalid command.')
            player_or_pc = input('Enter u to have yourself play, c to have the computer play: ')                  
        if player_or_pc == 'u':
            print('player played the game')
        elif player_or_pc == 'c':
            print('PC played the game')
        choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
    else:
        print('Invalid command.')
        choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')

【问题讨论】:

  • player_or_pc != 'u' or player_or_pc != 'c' - 此条件将始终为真。听起来你想要 and 而不是 or

标签: python while-loop logical-operators


【解决方案1】:

player_or_pc != 'u' or player_or_pc != 'c'总是正确的

  • 如果player_or_pc'u',则不等于'c',所以两个条件之一为真
  • 如果player_or_pc'c',不等于'u',所以两个条件之一为真
  • 任何其他值两个条件都为真

使用and

while player_or_pc != 'u' and player_or_pc != 'c':

或者用==,把整体放在括号里,前面用not

while not (player_or_pc == 'u' or player_or_pc == 'c'):

此时使用会员测试更清楚:

while player_or_pc not in {'u', 'c'}:

【讨论】:

    【解决方案2】:

    替换

    while player_or_pc != 'u' or player_or_pc != 'c':
    

    while player_or_pc != 'u' and player_or_pc != 'c':
    

    否则,player_or_pc 应该等于 uc,这是不可能的。

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 2022-11-12
      • 2015-05-18
      • 2017-12-09
      • 1970-01-01
      • 2014-12-22
      • 2015-06-25
      • 2017-12-09
      • 1970-01-01
      相关资源
      最近更新 更多