Problem with an elif during test run


When guessing a row and column which are not 0-4 it should hit else and print, but in stead I get the following error. (line 31 is 'elif board[guess_row][guess_col] == "X":' )

[snip] line 31, in <'module'> IndexError: list index out of range

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

Without elif it functions properly, why?


Changed it to if hit, elif in range, elif already guessed and else miss, now it works.
Could somebody explain why, because i'm not really seeing what's wrong with the previous code.


good that you made it work, the problem was in this line:

elif board[guess_row][guess_col] == "X":

if row and col are to high, you access a index in a list which doesn't exist, which is why not in range should come first


Ah, yes I get it. Thank you.
Seems like errors in coding are always way simpler to solve than they look

So instead of if hit, elif in range, elif already guessed and else miss
it could also be i.e. if hit, else: if in range, elif already guessed and else miss
as long as it reaches the in range before already guessed it's fine.


i would actually do in range as first, given you don't want to hit something which is off the board


But randint will always be in range of the created board (via len()), so there's no need for that, right?


this line:

if guess_row == ship_row and guess_col == ship_col:

guess_row and guess_col are the user choice, the first thing i do is always validate user input. Never trust a user.


Ok, function wise it's no real difference but I see your point.
So the best thing to do would be to check if in range, then elif hit and then the rest.


good code design is very important, good you see my point :slight_smile: I know the exercise doesn't ask it of you, but still


2 posts were split to a new topic: Not again