首页 > 解决方案 > 当列表不包含 if 语句指定的条件时,为什么会触发这个 if 语句?

问题描述

为什么触发第一个 if 语句而不是它之后的 elif 语句?

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]))

标签: pythonlistif-statement

解决方案


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

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

改成

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

所以

True and True and True

中的同样问题elif

elif 2 and 5 in computer_moves and 8 not in player_moves:如同

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


推荐阅读