Home > database >  Why is this if statement being triggered when the list does not contain the conditions the if statem
Why is this if statement being triggered when the list does not contain the conditions the if statem

Time:11-14

Why is the first if statement being triggered and not the elif statement after it?

player_moves = [1, 3, 4]
computer_moves = [5, 2]
if 4 and 5 in computer_moves and 6 not in player_moves:
    computer_moves.append(6)
    print("Computer chooses "   str(computer_moves[-1]))
elif 2 and 5 in computer_moves and 8 not in player_moves:
    computer_moves.append(8)
    print("Computer chooses "   str(computer_moves[-1]))

CodePudding user response:

if 4 and 5 in computer_moves and 6 not in player_moves: is same as

if 4 and (5 in computer_moves) and (6 not in player_moves):,

change to

if 4 in computer_moves and 5 in computer_moves and 6 not in player_moves:

so

True and True and True

Same problem in the elif.

elif 2 and 5 in computer_moves and 8 not in player_moves: same as

elif 2 and (5 in computer_moves) and (8 not in player_moves):

CodePudding user response:

Ok so:

In your IF statements you have the conditions (4 and 5) and (2 and 5). Your mistake is quite common. Instead of your code checking whether BOTH 4 and 5 are in the list computer_moves, it actually evaluates the boolean expression (4 and 5) which returns True, and then checks if True is in computer_moves.

You need to change your IF statements to:

if (4 in computer_moves) and (5 in computer_moves) and (6 not in computer_moves):
  • Related