It is giving me out of bound error everytime, why?


#1



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!"
    guess_row = "X"
    guess_col = "X"
    print_board(board)
    if guess_row not in range (5) or \
       guess_col not in range(5):
           
            print "Oops, thats not even in the ocean."


#2

Please post the link of the exercise next time.

You were asked to write the code in this way:

So what I would change is add an if-else statement under the else statement. First is to move the if statement under the else, and write the following code under the else statement of the else statement.

print "You missed my battleship!"
    guess_row = "X"
    guess_col = "X"
    print_board(board)

And your code doesn't change the Os to Xs at all. guess_row and guess_col do not refer to the exact position on the board, you defined them as numbers here:

guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

So in order to change the Os to Xs, you need to use another way to get the exact position on the board.
In this way, it's as similar to accessing an object in a list.

Example:

food = ["cake", "pie", "donuts"]

In order to access "pie", we would write food[1].
Similarly, to access the coordinate, we would write board[guess_row][guess_col], where guess_row and guess_col are numbers.
All that you need to do is assign "X" to that coordinate.

Example:
Say we want to change "pie" to "strudel". What we would do is this food[1] = "strudel".


#3

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


#4

can you tell me what is wrong here?


#5

That code is in the wrong place. It should be above all the checks except Win.


#6

before even adding that code... i am getting error, i think there is some problem with
guess_row = "X"
guess_col = "X"
print_board(board)


#7

As you have explained.... i did some changes,
print board[3][3]
https://www.codecademy.com/en/courses/python-beginner-en-4XuFm/1/2?curriculum_id=4f89dab3d788890003000096
please check this


#8

hey... this worked for me...
thanks


#9

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