'break' in an 'if' statement
I am taking the Python course on Codeacademy.com. I am totally new to programming. We are designing a small version of the game 'Battleship' and everyone in the forums seems to be stuck on the same part. It asks you to insert a break statement within an 'if' statement. After days of checking my indentation and code, I came found this answer within your pages:
So, here is my code:
for turn in range(4): print turn+1 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 sunk my battleship!" if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5): print "Oops, that's not even in the ocean." elif(board[guess_row][guess_col] == "X"): print "You guessed that one already." else: print "You missed my battleship!" board[guess_row][guess_col] = "X" # Print (turn + 1) here! print print_board(board) if turn >4: print "Game Over"
The instructions ask for a 'break' to be inserted directly under the print statement "Congratulations! You sunk my battleship!"
Now, if I run the code without the break statement it works fine. If I run the code with the break statement, the game works but at the says "oops. did you insert a break statement?"
Quite a few others can't seem to get past this error either, and the moderator on the forum insists on saying that there is no bug in the program.
So, to the experts out there, please tell me if I'm right, i.e., that a break statement will not work within this if statement as the post in this forum suggest.
I apologize for being verbose, but I want to give the exact issue so I can go back to Codeacademy with an answer!
You need to indent your if statements if they are to be part of the for loop:
for turn in range(4): print turn+1 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 sunk my battleship!" break # other if statements
Now the break statement is also within the for loop and can actually have an effect.