Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My while loop is repeating over and over again

it is referencing a board to a game with 9 slots and once the slots get filled up the ##while loop keeps searching for a new spot when there aren't any empty spots and I don't know how to fix it, please help! :(

        computer = random.randint(0, 8)
        if board[computer] != 'X' and board[computer] != 'O':
            print computer
            board[computer] = 'O'
        else:
            while board[computer] == 'O' or 'X':
                counter = 0
                if counter > 15:
                    break
                computer = random.randint(0, 8)
                print computer
                if board[computer] != 'X' and board[computer] != 'O':
                    board[computer] = 'O'
                counter += 1
like image 890
user1861771 Avatar asked Mar 07 '26 22:03

user1861771


1 Answers

Your while statement always returns a true value because the or 'X' always evaluates to True. First, board[computer] == '0' is evaluated, and if False, it proceeds to the right side of the or, which is simply the string X. You do have this pattern correct elsewhere in your code, so I suspect this was just an oversight.

Instead you must include both sides of the boolean comparison:

while board[computer] == 'O' or board[computer] == 'X':

Or better, you can use in

while board[computer] in ['O','X']:

Or, courtesy of @icktoofay in the comments, the idiomatic:

while board[computer] in 'OX':

Your counter must be initialized to 0 outside the loop, rather than reinitialized inside.

 # initialize outside the loop
 counter = 0
 while board[computer] == 'O' or 'X':
    # Don't re-initialize to 0 in the loop
like image 173
Michael Berkowski Avatar answered Mar 10 '26 13:03

Michael Berkowski