11 Danger, Will Robinson problem


#1



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


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


I think my code should work but it isn't, it seems that it gives me a pass if I guess the row and col correctly but not when I guess incorrectly. Also, sometimes it seems to not give me that error message but instead an error that says I did not print "You missed my battleship" when I did


Replace this line with your code. 
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_board(board)


#2

what exactly is your question? The code which checks if the user input is within the board (ocean) still has to be build. so if you enter valid coordinates is fine, catching the false coordinates is for later and should not be entered at this point


#3

Not entirely sure what your question is, the code looks fine to me. As for the last string you're printing, you are missing a !.


#4

My question was why am I getting the error mentioned above


#5

i did explain? If you enter coordinates which are not part of the board, you try to access a multi-dimensional list with impossible values, but the list isn't that long, so you get a indexerror (index doesn't exist)


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.