Danger, Will Robinson! - "Oops, try again. Make sure to enter a col and row that is on the board!"


#1



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


I got the code to mark incorrect guesses with X on the grid, but now I get this error message.

"Oops, try again. Make sure to enter a col and row that is on the board!"


I'm not really sure what it's asking me to do. I've tried printing both ship_row/ship_col and guess_row/guess_col at the end but I still get the same error message. Below is my code for this exercise in its entirety


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 - 1][guess_col - 1] = "X"
    print_board(board)


#2

Hello :slight_smile:

Your code is correct, in fact, it's better than what codecademy wants and that is the problem.

In this line:

board[guess_row - 1][guess_col - 1] = "X"

you have subtracted 1 from both indices to let users start indexing rows and columns from 1 which is a more natural way. Great idea. The problem is that codecademy needs to somehow check if your code is correct and to make this cooperation flawless you have to strictly follow instructions.

They asked you to:

Set the list element at guess_row, guess_col to "X".

and that's exactly what you need to do:

board[guess_row][guess_col] = "X"

And now, when you run the script you have to input indices from the range 0 - 4.


#3

omg it worked! Thank you so much! Here I was trying not to have a mental breakdown because I couldn't see what was wrong with my code. Seriously thank you :slight_smile:


#4

You're very welcome :slight_smile:

User saved from mental breakdown... I guess I can call it a day now :slight_smile: Good luck with next exercises and remember that there are many users here willing to help.


#5

I also think your code is better,but there is another problem that when inputing zero,your code will be wrong.My thought is:
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
elif 0 < guess_row < 6 and 0 < guess_col < 6:
print "You missed my battleship!"
board[guess_row - 1][guess_col - 1] = "X"
print_board(board)
else:
print 'Out of range!'


#6

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