12. Bad Aim



Traceback (most recent call last):
File "python", line 38, in
IndexError: list index out of range

I've looked through several other posts for this before posting my own and compared my code. It looks to be exactly the same as those who had success with their own. Here is another user's post where the only difference I can spot between his and mine is that he had the "You missed my battleship!" check before and after the "if guess_row not in range(5)" check.

The solution was for him to remove the first one so that the "if not in range" check would run immediately after the "Congratulations! You sank my battleship!" check.

That's what my code has so I'm stumped.

if guess_row == ship_row and guess_col == ship_col:
    print 'Congratulations! You sank my battleship!'
    if guess_row not in range(5) or guess_col not in range(5):
        print 'Oops, that\'s not even in the ocean.'
        print 'You missed my battleship!'
    board[guess_row][guess_col] = 'X'


but then you must only update the board:

board[guess_row][guess_col] = 'X'

when if condition is false, so updating board should be part of else clause. Currently is wrongly indented. Updating board is reached regardless if shot is on board or not

so index error can still occur


Wow I spent so much time comparing and still overlooked this, thanks!