Your code works because python don't have block scopes
. You can learn more about it on this thread: Block scope in Python
If you define your variable inside a while statement, it's the same thing as defining your variable at the global scope (in your case).
intInput = True
while intInput == True:
try:
# userInput here is global, because it's inside a while statement only
userInput = int(input())
intInput = False
except ValueError:
print('You must enter an integer.')
print(userInput)
Basically, the variable declared inside a "block scope", will have its scope from where it is being declared.
For example, if your code was inside a function, then the userInput
variable would have the function's scope, and then, your code would generate an error:
intInput = True
def do_your_thing():
while intInput == True:
try:
# userInput being declared here will have the function's scope
userInput = int(input())
intInput = False
except ValueError:
print('You must enter an integer.')
# you are trying to access userInput outside its scope
print(userInput)
Now, if you try to run this code, you'll see the error:
Traceback (most recent call last):
File "teste.py", line 28, in <module>
print(userInput)
NameError: name 'userInput' is not defined