Battleship, Oops that is not even in the ocean


#1

Okay, kind of a specific problem here. My problem is as follows:
If the player guesses a location that is not in range (on the board) my program should print "Ooops, that's not even in the ocean, and then it should move on to the next turn for the player to guess. My program prints "Ooops, that's not even in the ocean," but then it does not give the player another option on the next turn. Instead it returns an error because it tries to print "X" on the board for the players guess, however it the guess is out of range. The given error is list index out of range. I want the program to continue allowing guesses. Any help would be appreciated. Thank you so much. Here is my code:

from random import randint

board = []

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

def print_board(board):
[4 space indent]for row in board:
[8 space indent] print " ".join(row)

print_board(board)

def random_row(board):
[4 space indent] 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)
for turn in range(4):
[4 space indent]guess_row = int(raw_input("Guess Row:"))
[4 space indent]guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col


if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
else:
    if guess_row not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean."
    elif guess_row not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean..."
    elif board[guess_row][guess_col] == "X":
        print "You guessed that one already."
    else:
        print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print_board(board)
print "Turn", turn + 1

**Side question: How does the program know what the turn varible is? I have not set it (i.e. turn = something) to anything.

Thanks you so much in advanced for all the help!!!


#2

Update: I understand why turn is variable. I assigned it as one earlier in the code when I used it as a for loop.