Test Run strange errors


#1



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


When I enter guesses for the columns and rows, I get different errors every single time, or sometimes it works correctly, and sometimes it does place the X on the board, but not at the indices I specified

First of all I test the code a couple of times by entering 4 and 4 as my guesses. The first time it places the X correctly:

O O O O O
O O O O O
O O O O O
O O O O O
O O O O X

But when I redo using the exact same steps, I obtain:

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
2
0
Guess Row: 4
Guess Col: 4
2
0
You missed my battleship!
O O O O O
O O O O O
O O O O O
O O O O O
X O O O O
None

The third time I obtain:
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
5
5
Guess Row: 4
Guess Col: 4
5
5
Traceback (most recent call last):
File "python", line 37, in
IndexError: list index out of range

For guesses 0,0 it also places it incorrectly, some of the time:
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
4
4
Guess Row: 0
Guess Col: 0
4
4
You missed my battleship!
O O O O X
O O O O O
O O O O O
O O O O O
O O O O O
None

Basically sometimes I get the error, and other times it places the X in an incorrect column.


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) -1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

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!"
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 board[guess_row][ship_col] == 'X':
        print "You guessed that one already."
    else:
        print "You missed my battleship!"
        board[guess_row][ship_col] = 'X'
        print_board(board)


#2

Did you mean to write,

board[guess_row][guess_col])

?


#3

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