16. Game Over, scope of variable "turn"


This is a working code of the ex 16. But I am confused why this is working..

We have never declared a variable turn, but it is still accessible when we jump out from to for loop after 4 turns because "Game Over" is printed, eg. turn is declared and has a value of 3.

So in python when we write for turn in range(4): are we declaring turn as a global variable?

# Write your code below!
for turn in range(4):
    print "Turn", turn + 1 # Print (turn + 1) here
    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 sank my battleship!'
        if 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 guessed that one already."
            print "You missed my battleship!"
            board[guess_row][guess_col] = "X"

if turn == 3:
    print "Game Over"


Variables are just names, there's no declaring them. You do of course have to assign them to values before reading their values.

Since that code is written at the top level of the file (not in a function or class) then yes, you will have defined turn globally for that module (each module (file) has its own namespace)


Thanks for your reply!
Ah yes of course its in the top level, did not think of that, thanks for pointing that out.
When I said declaring i men assigning them, sorry mixed them up.

I think I might be confusing things here but in the expression below are we assigning a list to the variable turn ?

for turn range(5):

Eg. we are basically doing turn = [0,1,2,3,4] inside the for loop?

So our iterating variable "turn" will be accessible for us later?

What if we have assigned a variable "turn" higher up in our function will it be overridden? Do we need to be careful what we name our iterating variable?


No, the for-loop will repeatedly ask for next value from the iterable and assign each such value to the variable that you named

It behaves the same, is the same, as any other variable, including assigning multiple times to it

Variables representing different things shouldn't have the same names, so conflicting names is not a problem you should be having, it'd just be an indication of a different problem. But you may need to qualify one or both a little more if for example you want to track both the best bunny and be looping through various bunnies


Thanks! That made it all very clear to me
appretiate it!


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