无法分配给运算符.python的if语句中有多个分配

时间:2018-12-25 07:36:25

标签: python-3.x if-statement variable-assignment multiple-assignment

第4个elif结尾出现了无法分配给操作员的错误。我正在尝试设计井字游戏,并根据玩家的选择分配X和0。can't assign to operator

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)

3 个答案:

答案 0 :(得分:0)

您的所有分配行均为无效语法。 and是布尔运算符,您不能在表达式中间混入一个赋值。如果您确实要在一行上分配所有内容,请使用;

temp_player1 = 'Player1'; player1_marker = 'X'; temp_player2 = 'Player2'; player2_marker = '0'

这与您所有的if有关。

答案 1 :(得分:0)

在每个if语句中删除and运算符,并用分号替换; as和是运算符,它使python分配和分配变量变烦

更正后的代码为:

request.File.ContentType

答案 2 :(得分:0)

将作业分配到不同的行:

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中的工作原理,将多个语句放在一行不是很常见