Battleship - if Logic


RE: Battleship - Not Again!

I’m currently on step 13/19. I’m expected to write an elif statement asking to check if X is matching to the location of the guessed row and col. I’ve been given the clear up to this point, but the if statement doesn’t seem to make any sense to me.

if guess_row == ship_row:
  if guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    if guess_row not in range(5) or guess_col not in range(5):
      print "Oops, that's not even in the ocean."
      print "You, missed my battleship!"

My understanding of the if logic is this…

if the condition is met, go inside and keep working. else, move on and do this.

So, the code, which has been cleared by the course, to me shows as this…

if the guess_row == ship_row go inside here and check if guess_col == ship_col, now go inside here and print “Congrats…”

Well, if the guess_row != ship_row, it should immediately return False and not move on.

My lesson is asking me to check if the guess_row and guess_col position in board contain the X string. The next lesson says it’s a fully functional version of Battleship for a single guess. The logic indicates otherwise. If that guess_row doesn’t match, the game should stop immediately.

What am I missing?



I’m not sure what you’re asking. My best guess is that you’re observing that the functional testing of your code is incomplete.


The very first line of the if statement…

if guess_row == ship_row:

If that condition is not met, we shouldn’t even get inside to do the rest of the checks.

So, if ship_row is set to 3… the user enters 4

guess_row does not equal ship_row, so we shouldn’t go inside of that block of code.

Another way:

number = int(raw_input("Enter number: "))

if number < 5:
  if number == 3:
    print "You win."

If the user enters “7”, then number is not less than 5, the condition is not met, therefore there is no need to check if the number is 3.

Basically, the user enters their guess for the ship’s row. If that doesn’t match what is in ship_row, it should not proceed inside the rest of the code.


I’m starting to think there’s a bug that allowed me to proceed with that code. Now that I’m at lesson 17/19, the indentation has changed. I might have to go back and submit the report.


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