Python Tutorial_ Global vs. Local Variables and Namespaces
Python Tutorial_ Global vs. Local Variables and Namespaces
Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact
x = 3
f()
print("x in main: " + str(x))
Before calling g: 42
Calling g now:
After calling g: 43
x in main: 3
Python Training In the previous example the variable x was defined prior to the call of g. We get an error if it isn't defined:
Courses in Toronto,
def f():
Canada
#x = 42
On site trainings in def g():
Europe, Canada and nonlocal x
the US. x = 43
print("Before calling g: " + str(x))
print("Calling g now:")
g()
print("After calling g: " + str(x))
Think Globally,
Act Locally x = 3
f()
"Think Globally, Act print("x in main: " + str(x))
Locally" is an urgent
request to people to We get the following error message:
consider the health of File "example3.py", line 4
the entire planet and nonlocal x
to take action in their SyntaxError: no binding for nonlocal 'x' found
own environment,
i.e. local communities The program works find - with or without the line "x = 42" inside of f - , when we change "nonlocal" to "global":
and cities.
def f():
But this principle #x = 42
def g():
should be a guiding
global x
line to programming x = 43
both in Python and print("Before calling g: " + str(x))
and other print("Calling g now:")
programming g()
languages as well. print("After calling g: " + str(x))
x = 3
f()
print("x in main: " + str(x))
Calling g now:
The value of x after the call to g: 43
Before calling g: 3
Calling g now:
After calling g: 43
x in main: 43
Yet there is a huge difference: The value of the global x is changed now!
© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein