PyPuzzle 001 Scope
This weeks PyPuzzle will test your knowledge of order of execution, operator precedence, and scope.
- Execution Order: Tracking the order of statements and the effect of function calls.
- Operator Precedence: Understanding how
x = x + y
works whenx
is global. - Variable Scope: Understanding
global
,nonlocal
, and local scopes.
Feel free to use an online Python compiler and interpreter like [this] (https://www.online-python.com/) to try running the code yourself. The answer is supplied below the code.
Question
What is the expected output of the following code?
x = 5
def puzzle():
global x
y = 10
x = x + y
def inner():
nonlocal y
y = 20
print("Inside inner:", x, y)
inner()
print("Inside puzzle:", x, y)
puzzle()
print("Outside puzzle:", x)
Answer
After puzzle()
runs:
-
x
in the global scope is updated to15
(fromx + y = 5 + 10
). -
inner()
modifiesy
inpuzzle()
to20
. - The
print()
insideinner()
outputsInside inner: 15 20
. - The
print()
insidepuzzle()
outputsInside puzzle: 15 20
. - Finally,
print("Outside puzzle:", x)
outputsOutside puzzle: 15
.
Expected output:
Inside inner: 15 20
Inside puzzle: 15 20
Outside puzzle: 15
Learnings
- That different parts (functions) of Python code have different world views (scopes).
- These scopes are defined by the level of the function (indicated by indentation) and the level of the variable (indicated by keywords like
global
andnonlocal
).
Enjoy Reading This Article?
Here are some more articles you might like to read next: