Python 2.7.5 OR运算符有些问题

时间:2013-10-26 05:26:26

标签: python comparison-operators

所以,我正在重新设计我最近创建的tic-tac-toe游戏,以获得更简洁和优化的代码。但是,当任一玩家移动到空白区域时,我在使用OR语句时遇到了一些麻烦

(很少有快速的注释:在我的代码中,user_team和computer_team等于'X'或'O',具体取决于玩家选择的团队,并且棋盘上的每个空间等于''默认)

如果我这样运行代码:

move = int(raw_input('Where would you like to move? (Enter a number from 1-9) \n'))
if 0 < move < 10:
    if board[move] == user_team:
        print ('That space is already taken by a player.'
               'Please select an open space \n')
        user_turn()
    elif board[move] == computer_team:
        print ('That space is already taken by a player.'
               'Please select an open space \n')
    else:
        board[move] = computer_team
        print
else:
    print ('That is not a valid move. Please try again. \n')
    computer_turn()

上面的代码完全按照预期运行,并将玩家移动分配给空格,或者如果占用空间则拒绝。

但是,如果我缩短这样的代码:

move = int(raw_input('Where would you like to move? (Enter a number from 1-9) \n'))
if 0 < move < 10:
    if board[move] == user_team or computer_team:
        print ('That space is already taken by a player. '
               'Please select an open space \n')
        user_turn()
    else:
        board[move] = computer_team
        print
else:
    print ('That is not a valid move. Please try again. \n')

然后代码将阻止玩家占用空白区域。实质上,代码说:

if ' ' == 'X' or 'O':

但它的行为似乎是真的,即使它显然是假的。

SideNote:万一有人问,这就是我画板的方式:

def draw_board():
print '', board[1], '|', board[2], '|', board[3], \
      '\n-----------\n', \
      '', board[4], '|', board[5], '|', board[6], \
      '\n-----------\n', \
      '', board[7], '|', board[8], '|', board[9], \
      '\n'

和board是十个' '

的列表

1 个答案:

答案 0 :(得分:1)

更改

if board[move] == user_team or computer_team:

if board[move] in [user_team, computer_team]:

if board[move] == user_team or computer_team将被评估为(board[move] == user_team) or (computer_team),因为computer_team始终评估为Truthy值,此条件将始终为True。

通过使用in运算符,我们确保board[move]位于后面的项目列表中,其中包含user_teamcomputer_team。如果它不在该列表中,则返回False。