Not iterating over Turn variable in While loop?


def battleship():
	while turn < 4:
		guess_row = int(raw_input("Guess Row:"))
		guess_col = int(raw_input("Guess Col:"))
		print "Turn", turn + 1
		print "Ship Row: %s" % (ship_row)
		print "Ship Col: %s" % (ship_col)
		if guess_col == ship_col and guess_row == ship_row:
			print "Congratulations! You sank my battleship!"
		elif board[guess_row][guess_col] == "X":
			print "You guessed that one already."
		elif guess_row not in range(5) or guess_col not in range(5):
			print "Oops, that's not even in the ocean."
		elif board[guess_row][guess_col] != "X":
			print "You missed my battleship!"
			board[guess_row][guess_col] = "X"
			print "Game Over"

My problem is in the very beginning of the while loop, it's not adding 1 to turn at each iteration of the loop. It simply prints turn and adds 1 once, each time as if it were the first instance. So my game won't break unless I successfully sink my battleship, otherwise everything else works as its supposed to.

Am I using my while loop incorrectly?


Why would turn be increased, do you have any code that says to do so? If you don't, then it shouldn't, right?


This is just a thought... Let this else be part of the while statement, and not inside the while statement only, and at the very end,


    while turn < 4:
        if / elif statements (may contain `break`)
        print turn + 1
        print "Game over"

The last line will not need a break since it is outside of while.


Thanks wasn't sure how to end my while loop. My supposed line to add turn is a couple lines under while. I tried to print "Turn", turn += 1
But it threw an error. I know this works inside a for loop, shouldn't it loop over this line as well inside a while loop? Outside of while turn = 0 so I know that it is adding one and printing it, but it's not saving it to the variable.


You know... Now that we look at it, turn is not defined in the posted code.

It ends when the indentation ends. else is not a way to end a while statement, but to provide an action the does not coincide with a break inside the loop. It is an alternate ending, as it were (default, actually) of the while statement.

print "You win!"

would bypass the else.


Assignment in Python is a statement so it has no result that you can then print, so no, you can't do that.
Print it in one place and change it in another. Two separate actions.

Other languages may differ. They're other languages.


I just went and checked the code we built way back when. It used a for statement with range(4). That's why we printed, 'Turn', turn +1. In the case of a while loop, @ionatan has a good point.

print 'Turn', turn + 1
turn += 1


Oh good! That was the difference. Guess I need to research more about how while, for, handles information. Like you were saying @mtf