Working syntax but question

While doing this problem, I did some tweaks to my code as follows:

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)


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:")) - 1
guess_col = int(raw_input("Guess Col:")) - 1

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


Specifically, i used "guess_row = int(raw_input("Guess Row:")) - 1
guess_col = int(raw_input("Guess Col:")) - 1" so that the guess corresponds to the actual location rather than the index, and " if guess_row not in range(4) or guess_col not in range(4): print "Oops, that's not even in the ocean."" , so that the checker for out of range guesses correspond to the actual location too.

Hopefully it makes sense so far.

Then when I entered my guess as [5] [5] in the game, it prints "Oops, that's not even in the ocean". I don't quite understand why. The guess I entered should be raw_input("Guess Row:") and raw_input("Guess Col:") (if my assumption is correct), which generates 4s for guess_row and guess_col, which fall into range(4). How did it trigger "Oops"?


Keep the original range of 5. Once your subtract 1 from the inputs, the remaining code should be as originally written.


I have a hard time grasping it conceptually, can you elaborate on it? My code is meant to check if guess_row is in range(4), and I don't see a reason why it's not if raw_input = 5 and guess_row = raw_input - 1


range(4) only includes, 0..3. but the board indices are, 0..4. If your program insists that the user enter, 1..5, then subtracting 1 puts those values in sync with the existing range.


Oops, I confused range() with some other function that implies a <= relation but I can't remember which one it is. Thanks!


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