14. Test run


#1

It says Traceback (most recent call last):
File "python", line 40, in
IndexError: list index out of range
when I write something more than 5 in the console. It doesn't work for me please help!

Here's my code:

Write your code below!

if guess_col == ship_col and guess_row == ship_row:
print "Congratulations! You sank my battleship!"

else:
if guess_row not in range(5) or \
guess_col not in range(5):
print "Oops, that's not even in the ocean."
elif board[guess_row][guess_col] == 'X':
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] == 'X' <<<<<===== This is line 40 and it doesn't work wherever I put it
print print_board(board)


#2

Are you trying to set board[guess_row][guess_col] to "X" with line 40?

For assigning a value to a variable use = not ==

Not sure why it tells you that the index is out of range though.


#3

Thank you for the response but it doesn't work even with =
and what does "index out of range" mean anyway?


#4

Say you have a list with 3 elements:

my_list = ["A", "B", "C"]

You can get one of the elements by using my_list[index]:

print my_list[0]  # prints "A"

But there are only elements at indexes 0, 1 and 2:

print my_list[4]

will cause an error because the index is out of range.


#5

Hi!
I had the same problem "IndexError: list index out of range".
As far as I could figure it out, it was due to the guess being outside of the matrix range.
I've tried several attempts to solve the error, until I tried a solution in an older topic.
I've reordered the nested "if/else" conditions and got it working like this:

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

On the first "Else", the only way to the code to work is if I put the verification of the guesses, are inside/outside the matrix, in first.
Can anyone explain me why? Why the checking of the range of the matrix must be in first, to avoid getting an error of "out of range"?


#6

If the guess_row and guess_col are outside the range of the lists then you ask to find an item in a list that isn't defined. That causes python to give the error. I don't know Python that well but it seems to be very strict on that point! So if you want to get something out of a list make sure you point to a place that exists.

Advantage is that the program is clear about it (out of range).