It prints congratulations, so why does it count it wrong?
Answer
There are a few reasons this could happen:
Be sure you are using the correct variable names, guess_row, ship_row, guess_col, and ship_col.
Your if statement needs a colon at the end, and the print statement inside of it should be indented.
The string you print inside the if should match the string in the instructions exactly - capitalization, spelling, and punctuation must be identical to what it’s checking for.
How come the code for the ‘random_col’ and ‘random_row’ functions has changed from exercise 8 onward?
Original code:
def random_row(board_in):
return randint(0, len(board_in) - 1)
def random_col(board_in):
return randint(0, len(board_in) - 1)
New code:
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
I assume the latter is how we differentiate the rows from the columns?
yes, now our board doesn’t have to be a square, it can be a rectangle. Which i personally think is better, that we can change the dimensions of our board freely, without it breaking the code
I was wondering how this code does this? Doesn’t ‘randint(0, len(board[0]) - 1)’ just mean a random number between 0 and the first index of ‘board’ minus 1? Or have I completely misunderstood this?
Hi I encounter this error intermittent while testing, please help to advice
"Traceback (most recent call last):
File “python”, line 26, in
ValueError: invalid literal for int() with base 10: ‘’
# My 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)
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: "))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
else:
print "Missed"
The exact same thing happens to me. It doesn’t print but the lesson completes. I’m pretty sure it’s just a site error. As long as you input the correct coordinates and have the print statement indented inside the for statement you should be golden.