无法分配给操作员 。python 中 if 语句中的多个赋值



第 4 个 elif 结尾抛出错误无法分配给运算符。我正在尝试设计一个井字游戏,并根据玩家的选择为其分配 X 和 0。无法分配给操作员

def player_input(player):
    marker = ''
    while(marker != 'X' and marker != '0'):
        marker = input('{},choose X or 0:'.format(player))
    if(player == 'Player1' and marker == 'X'):
        temp_player1 = 'Player1' and player1_marker = 'X' and temp_player2 = 'Player2' and player2_marker = '0'
    elif(player == 'Player1' and marker == '0'):
        temp_player1 = 'Player1' and player1_marker = '0' and temp_player2 = 'Player2' and player2_marker = 'X'
    elif(player == 'Player2' and marker == 'X'):
        temp_player1 = 'Player1' and player1_marker = '0' and temp_player2 = 'Player2' and player2_marker = 'X'
    elif(player == 'Player2' and marker == '0'):
        temp_player1 = 'Player1' and player1_marker = 'X' and temp_player2 = 'Player2' and player2_marker = '0'
    else:
        pass
    return(temp_player1,player1_marker,temp_player2,player2_marker)

删除每个 if 语句中的 and 运算符并用分号替换它们 ; as and 是一个运算符,它扰乱了 python 赋值和变量

更正后的代码将是:

if(player == 'Player1' and marker == 'X'):
    temp_player1 = 'Player1' ;  player1_marker = 'X' ; temp_player2 = 'Player2' ; player2_marker = '0'
elif(player == 'Player1' and marker == '0'):
    temp_player1 = 'Player1' ; player1_marker = '0'; temp_player2 = 'Player2' ; player2_marker = 'X'
elif(player == 'Player2' and marker == 'X'):
    temp_player1 = 'Player1' ; player1_marker = '0' ; temp_player2 = 'Player2' ;player2_marker = 'X'
elif(player == 'Player2' and marker == '0'):
    temp_player1 = 'player1'; player1_marker = 'X' ;temp_player2 = 'Player2'; player2_marker = '0'
else:
    pass

将您的作业分成不同的行:

if(player == 'Player1' and marker == 'X'):
    temp_player1 = 'Player1'
    player1_marker = 'X'
    temp_player2 = 'Player2'
    player2_marker = '0'
elif(player == 'Player1' and marker == '0'):
    temp_player1 = 'Player1'
    player1_marker = '0'
    temp_player2 = 'Player2'
    player2_marker = 'X'
elif(player == 'Player2' and marker == 'X'):
    temp_player1 = 'Player1'
    player1_marker = '0'
    temp_player2 = 'Player2'
    player2_marker = 'X'
elif(player == 'Player2' and marker == '0'):
    temp_player1 = 'player1'
    player1_marker = 'X'
    temp_player2 = 'Player2'
    player2_marker = '0'
else:
    pass

您应该阅读缩进在 Python 中的工作原理 为了可读性,将多个语句放在一行中并不常见

相关内容

  • 没有找到相关文章

最新更新