14.Test run


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,4)

def random_col(board):
    return randint(0,4)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
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 not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean."
            print "You missed my battleship!"
    board[guess_row][guess_col]= "X"

print ship_row
print ship_col


I don't know why when I put numbers outside the range(0,4) like 6 in my example or any number , it throws an error ?
What did I do wrong in my code, everything seems in order, it's just when I put something out of the range ! though I already put the not in range code in correctly, someone help thanks



The problem comes from the fact that you are testing elif board[guess_row][guess_col] == "X": before testing if the rows and columns are inside the range. You should test if the guessed row and column are inside the range BEFORE testing if the set of guessed row/column is equal to "X".
In you code, when you enter a set of row/column outside of the range, then the line elif board[guess_row][guess_col] == "X": is executed and the code is faced with an index which is bigger than the size of board. This explains the error message that you get : line 26, IndexError: list index out of range.