Functions: Global and Local Scope (Livehacking Screenplay)

Undefined Variable

Using a name that is not defined (neither in local nor in global scope) leads to an error:

def f():
    print(x)

f()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 4
      1 def f():
      2     print(x)
----> 4 f()

Cell In[1], line 2, in f()
      1 def f():
----> 2     print(x)

NameError: name 'x' is not defined

Local Variable

x defined locally:

def f():
    x = 1
    print(x)

f()
1
  • Rule: when a name is assigned to the first time, it is created in that scope where the assignment takes place.

  • x is a local variable

  • This is not Javascript where one has to use let to prevent accidental creation of a global variable

Global Variable

If a name is not defined locally, Python continues to lookup in global scope:

def f():
    print(x)

x = 42
f()
42

Note: x must be visible at call time, not at definition time

Local and Global Variable With Same Name

Local variables shadow global variables:

x = 666

def f():
    x = 1
    print('local:', x)

f()
print('global:', x)
local: 1
global: 666

Assignment to Global Variable: global

  • How do I assign to a global variable then, if assignment creates a variable in local scope?

  • global keyword

  • See here for a description of the nonlocal keyword

x = 666

def f():
    global x
    x = 1
    print('assigned global:', x)

f()
print('global:', x)
assigned global: 1
global: 1