Bad Aim


#1



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


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
Guess Row: 8
Guess Col: 8
2
2
You missed my battleship!
Traceback (most recent call last):
File "python", line 33, in
IndexError: list index out of range


I entered 8 and 8 for the row and col, and I was expecting it tells me that "Oops, that's not even in the ocean." However, it showed the message of "File "python", line 33, in IndexError: list index out of range" instead. Can someone help to tell me what's going on? Thanks!


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)
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:
    print "You missed my battleship!"
    board[guess_row][guess_col]="X"
    print_board(board)
    if guess_row not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean."
    else:
        print "You missed my battleship!"
        board[guess_row][guess_col]="X"
        print_board(board)


#2

I kinda understand why. Is it because the board is only 5x5, so anything beyond 4 in row and 4 in col, the system is going to say the index is out of range?
Because I tried something myself. I tried to change range(5) to range(1) for both guess_row and guess_col, then I tried to enter 3 and 3 for row and col. Then the system printed out "Oops, that's not even in the ocean." I understand this as that (3,3) is on the board(on the original post, I mentioned (8,8) which is not even on the board since it's out of 5x5 board. I guess that's why it didn't print out "Oops" sentence.) but (3,3) is out of range(1) I set up, so it shows the "Oops" sentence. Can someone understand what I'm trying to say? and if you do, can you please verify whether what I think is correct? Thanks!


#3

This segment of code is repeated, and the one above the range test should be removed. As long as you test the range before any other checks, it will catch values outside of the accepted range.


#4

Removed it, and test it again, got it right. Thanks


#9