while循环或条件

时间:2018-06-11 12:12:14

标签: python while-loop logical-operators

在第二个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: ')

2 个答案:

答案 0 :(得分:4)

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'}:

答案 1 :(得分:1)

替换

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

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

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

相关问题