Dr. Cho’s Website
Course Materials

Variable scoping in Python

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Global variables

Global variables are available “globally.”

def f():
  print(a)
a = 'Global?'
f()

Try to change a global variable.

def f():
  a = 'Local!'
  print(a)
a = 'Global?'
f()
print(a)

1.1   Global and local

You cannot access the same variable globally and locally.

def f():
  print(a)
  a = 'Local!'
  print(a)
a = 'Global?'
f()
print(a)

Any variables that are assigned or modified inside a function become local.

1.2   Explicit declaration

You can modify global variables inside a function.

def f():
  global a
  print(a)
  a = 'Modified global'
  print(a)
a = 'Global?'
f()
print(a)

2   Local variables

Local variables are only accessible from where they are defined.

def f():
  a = 'I am local!'
  print(a)
f()
print(a)

3   Nonlocal variables

Nonlocal variables are similar to global variables, but you cannot modify them from a nested function.

def f():
  a = 'Local'
  print('Inside f: ' + a)
  def g():
    nonlocal a
    a = 'Modified local'
    print('Inside g: ' + a)
  g()
  print('Inside f: ' + a)
a = 'Global?'
f()
print(a)

3.1   Nonlocal vs. global variables

Global variables are modifiable anywhere as long as they are declared as global.

def f():
  a = 'Local'
  print('Inside f: ' + a)
  def g():
    global a
    a = 'Modified global'
    print('Inside g: ' + a)
  g()
  print('Inside f: ' + a)
a = 'Global?'
f()
print(a)