Question

So, I'm reworking the tic-tac-toe game that I recently created to have more concise and optimized code. However, I'm having some trouble with an OR statement when having either player move on an empty space

(Few quick sidenotes: In my code, user_team and computer_team are equal to either 'X' or 'O' depending on which team the player chooses, and each space on the board equal to ' ' by default)

If I run the code as such:

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

The above code runs exactly as expected and will assign the player move to empty spaces, or refuse if the space is taken.

However, if I shorten the code like this:

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

Then the code will prevent a player from taking an empty space. In essence, the code is saying:

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

but it acts as if it is true, even though it is clearly false.

SideNote: Just in case anyone asks, this is how I draw my board:

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'

and board is a list of ten ' '

Was it helpful?

Solution

Change

if board[move] == user_team or computer_team:

to

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

This if board[move] == user_team or computer_team will be evaluated as (board[move] == user_team) or (computer_team), since computer_team always evaluates to Truthy value, this condition will be True always.

By using the in operator, we are making sure that board[move] is in the list of items that follows, which contains user_team and computer_team. If it is not in that list, it will return False.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top