Test Run



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)


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.")
    if guess_row in range(5) and guess_col in range(5):
        print("You missed my battleship!")
        print("Oops, that's not even in the ocean.")



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


sorry i dont get it :cry:


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


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


well, then this lines:

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

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


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.


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


i have modified my code now is this correct