16 - Game Over


#1



for turn in range(4):
    print "Turn", turn +1

I understand that the for loop is essentially telling the loop to run 4 times. I also understand that it is adding +1 to turn each time, however I don't really understand the logic of why it is also modifying the string "Turn" each time so that when the string prints it looks like this.

Let's play Battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O

Turn 1
Guess Row: 2
Guess Col: 2
You missed my battleship!
O O O O O
O O O O O
O O X O O
O O O O O
O O O O O
Turn 2
Guess Row: 3
Guess Col: 3
You missed my battleship!
O O O O O
O O O O O
O O X O O
O O O X O
O O O O O
Turn 3
Guess Row: 3
Guess Col: 1
You missed my battleship!
O O O O O
O O O O O
O O X O O
O X O X O
O O O O O
Turn 4
Guess Row: 4
Guess Col: 1
You missed my battleship!
O O O O O
O O O O O
O O X O O
O X O X O
O X O O O
None

The program works, i'm just trying to understand the logic behind that one part of the for loop.


#2

I think I understand.

for turn in range(4):
    print "Turn", turn +1

this part: print "Turn", turn +1

Is it printing "Turn" then concatenating the integer 1 into the print statement?

And also assigning and incrementing the value turn by 1 each the loop runs?

Stupid question I know, but sometimes just hearing someone explain something differently or confirming that your logic is correct can be useful.


#3

Hello Py A Thon :slight_smile: You got part answer right and part answer wrong :slight_smile: Let me explain:

When we loop using this method:

for turn in range(4):

turn variable takes values - 0, 1, 2, 3. Now, if you tell a non-programmer user that there would be four turns, and then you begin the first turn saying: Turn 0 (0 is the first value turn variable takes), wouldn't the user be surprised? For normal, non-programmer users, counting begins at 1. Thus, even though turn takes values 0, 1, 2, 3, you have to display the values as 1, 2, 3, 4. That is why, when displaying (printing), you are doing that +1 to turn variable's value.


No, it is not incrementing the value of turn variable. range(4) (used in the loop) automatically creates a list, which equals [0, 1, 2, 3] and then, per iteration of the loop, turn variable takes one value from that list in sequence (i.e., first 0, then 1, then 2, etc.) Even if you did turn = turn + 1 inside the loop, that wouldn't affect the next iteration (check).


"Concatenation" means to join literally, so 2 and 1 concatenated would give 21. Here, using turn + 1, we are doing simple mathematically addition (2 + 1 = 3).


I hope it helps! :slight_smile: