Problem with an elif during test run


#1

https://www.codecademy.com/en/courses/python-beginner-en-4XuFm/1/5?curriculum_id=4f89dab3d788890003000096

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_board(board)
    print "Congratulations, you sank the battleship!"
elif board[guess_row][guess_col] == "X":
    print_board(board)
    print "You guessed that one already, ya dingus!"    
else:
    if guess_row not in range(5) or \
    guess_col not in range(5):
        print_board(board)
        print "Oops, that's not even in the ocean."
    else: 
        board[guess_row][guess_col] = "X"
        print_board(board)
        print "You missed the battleship!"

Without elif it functions properly, why?


#2

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.


#3

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


#4

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.


#5

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


#6

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


#7

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.


#8

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.


#9

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


#10

2 posts were split to a new topic: Not again