Concepts of Programming Languages

(Sean Pound) #1

226 Chapter 5 Names, Bindings, and Scopes


if it has been declared to be global in the function. Consider the following
examples:
day = "Monday"

def tester():
print "The global day is:", day

tester()

The output of this script, because globals can be referenced directly in func-
tions, is as follows:

The global day is: Monday

The following script attempts to assign a new value to the global day:

day = "Monday"

def tester():
print "The global day is:", day
day = "Tuesday"
print "The new value of day is:", day

tester()

This script creates an UnboundLocalError error message, because the
assignment to day in the second line of the body of the function makes day a
local variable, which makes the reference to day in the first line of the body of
the function an illegal forward reference to the local.
The assignment to day can be to the global variable if day is declared to
be global at the beginning of the function. This prevents the assignment to day
from creating a local variable. This is shown in the following script:
day = "Monday"

def tester():
global day
print "The global day is:", day
day = "Tuesday"
print "The new value of day is:", day

tester()
The output of this script is as follows:

The global day is: Monday
The new value of day is: Tuesday
Free download pdf