# Test Run

#1

I am getting several error messages:

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

I expected line 34 to take care of the index error.
But for reasons I don't understand, it doesn't.
Does anyone know why?
Or does anyone know a better way to avoid the inder error?

(all the other functions work perfectly)

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)

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

playgame()

#2

this line:

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

which access your list by index, is before you validate that the shot is in the ocean, causing the problem

given you ask for better options, i would always first validate the user input, before progressing

#3

That does the trick.
This code works:

However † does not print to the console. But I guess I should use its unicode-number instead. Thanks!

#4

so, all sorted now or do you have further questions?

#5

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