Danger, Will Robinson


#1

Hi all, I cannot work out what I am doing wrong. It is the last block of code that I am stuck with.

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

I am getting the following error msg:

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

I just cannot work out why. I've had a look at other code posted here, i've moved the print statement at the bottom out and back in and it makes no difference. Any help would be much appreciated! I kind of know what the error is saying, but I don't understand why.


from random import randint

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col

# Write your code below!
if guess_row == ship_row and guess_col \
== ship_col:
    print "Congratulations! You sank my battleship!"
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print print_board(board)


#2

@razorwire,
Your code functioned

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
1
0
You missed my battleship!
O O O O O
O O X O O
O O O O O
O O O O O
O O O O O
None

#3

Yes, it functions, then at the end throws the error, disabling me from being able to move onto the next step. :frowning:


#4

just remind your indexes is in 1, ... , 5
you must enter a number between these no upper and no lower


#5

Hi, thanks for your reply. I'm not sure where you mean though. I tried changing it in "for x in range" etc but made no difference.


#6

just see your error:

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


now : "line 34" is:

board[guess_row][guess_col] = "X"

Error: IndexError: list index out of range
this is a list "board[guess_row][guess_col]", for example your list is:
[[0,0,0,0,0],[1,2,3,4,5,],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4]]

if you call board[1], will be return [1,2,3,4,5]
now, if you call board[1][2], will be return 3
now if you call board[1][6] or board[6][1] and any thing that are greater than 4 you get index out of range error.

this is sample example in python console:

>>> a = [1,2,3,4,5]
>>> a[1]
2
>>> a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

see this error is equivalent by your error.

i think this is your problem, please test again with numbers 1 and 2


#7

Thanks for your help. I played around with it a bit more and tried to understand the error like you said. It works now.