10. You win! [No error but question about exercise]


#1



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

So, my code is running fine and I'm passing the exercise. But how come when I guess the correct coordinates, my console prints 4 3 and not the expected "Congratulations! You sank my battleship!"?


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!"


#2

It wouldn't print "Congratulations! You sank my battleship!" because user's guess didn't satisfy the condition if guess_row == ship_row and guess_col == ship_col:

Hope this helps!


#3

That makes sense, but then if I guess for example, row 2 col 2, the console will print something like:
1
3
Why would it print (seemingly) random numbers?


#4

That should be the Computer's random guess.

Putting else/elif statement(s) (along the course I believe), to handle other scenarios might help you appreciate what this condition does upon user's guess. :smiley:


#5

Okay, thank you so much! Sometimes even when I get the code correct, I still don't fully understand the programs logic! But you've helped a bunch!


#6

Yeah, understanding it is key! You're welcome.

Keep on! :smiley:


#7

hello, I chanced upon this conversation and decided to give it a shot myself :slight_smile:

I got this code:

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)

print ship_row
print ship_col

ship_row = random_row(board)
ship_col = random_col(board)
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!"

which allowed me to cheat since I printed the system's guess first before having to input my guess. Why then is the Congratulations message not appearing? Thanks :slight_smile:


#8

i have the same code but it says that ship_row is not defind


#9

Let's see your own code (saying is same might be a false assumption)

Thank you!