0
  • Mac OS 10.13.16
  • Python 3.7
  • PyCharm

I was going through a tutorial for this guessing game and I came across something I thought was weird. On line 18 I call on the guess variable, which I though was a Local Variable under the for loop created above it, let's me call on it as if it were a Global. I though if a var is declared within a function or loop it makes it a local. Can someone help explain this to me.

import random
print("Hello what is your name?")
name = input()
print("Well " + name + " I am thinking of a number between 1 and 20")
secretNumber = random.randint(1,20)

for guessesTaken in range(1, 7):
    print("Take a guess.")
    guess = int(input())
    if guess < secretNumber:
        print("Sorry to low")
    elif guess > secretNumber:
        print("Sorry to high")
    else:
        break


if guess == secretNumber:
    print("Great job " + name + ". You guessed my number in " + str(guessesTaken) + " moves.")
else:
    print("Sorry the number I was thinking of is " + str(secretNumber))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

1

Taken from another answer: It appears to be a design decision in the python language. Functions still have local variables, but for loops don't create local variables.

Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.

http://mail.python.org/pipermail/python-ideas/2008-October/002109.html

aaldilai
  • 271
  • 1
  • 6
0

Excerpt from Python's documentation:

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c’ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.

And:

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name.

When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.

Local variables are visible anywhere in the same code block. A for loop is not a code block by definition, however, and therefore the local variable defined in your for loop is still visible after the loop, within the same module.

blhsing
  • 91,368
  • 6
  • 71
  • 106