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 when x 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:

  1. x in the global scope is updated to 15 (from x + y = 5 + 10).
  2. inner() modifies y in puzzle() to 20.
  3. The print() inside inner() outputs Inside inner: 15 20.
  4. The print() inside puzzle() outputs Inside puzzle: 15 20.
  5. Finally, print("Outside puzzle:", x) outputs Outside 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 and nonlocal).