Test Run


#1



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


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


I entered 3, 3 and this error came out but it passed in previous exercise please help


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


#2

here:

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

you access the board with indexes, but you verify later that the shot is on the board, it should be on the other way round


#3

sorry i dont get it :cry:


#4

well, this is currently your game flow:

check if ship is ht
check if the user guessed these coordinates before
check if guess is on the board
you missed

you check if the user guessed these coordinates before, earlier then validating if the shot is on the board

so if the users enters something invalid (8) the guessed this coordinates before gives an index error, you should first verify the shot is on the board, before check if the user guessed that one already


#5

oh get it, but why the code work when i enter value less than 5?(inside the range)


#6

well, then this lines:

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

doesn't cause an IndexError (which crashes the program)


#7

because the code only works when i enter the value that less than 5, but it gives error when the value is more than 5.


#8

which is why you added:

if guess_row in range(5) and guess_col in range(5):

to prevent the IndexError, but this only works if you do this before accessing the board by indexes


#10

i have modified my code now is this correct


#11