Python is unique in the way it uses global and local variables. While in many or most other programming languages, variables are treated as global if not otherwise declared, Python treats variables in the opposite way. If not declared otherwise, they are local. The driving reason behind this approach is that global variables are generally bad practice and should be avoided. In most cases where you want to use global variables, it's better to use parameters to put values into a function or return values to get them out. Like many other program constructs, Python imposes good programming habits by design.
Therefore, when you define variables in a function definition, by default they are local to that function. That is, any operations you do on such variables in the function body will not affect other variables outside the function, even if they have the same name. In other words, the function body is the scope of such a variable, i.e., the enclosed context in which that name is associated with its value.
All variables have block scopes where they are declared and defined. They can only be used after the point of declaration.
A quick note: variables do not have to be and cannot be declared in the same way as they are declared in programming languages such as Java or C. Variables in Python are declared implicitly by defining them, i.e., the first time a value is assigned to a variable, that variable is declared and automatically has the datatype of the object to which it must be assigned. If you have problems understanding this, see our section on data types and variables, see the link on the left.
Global and local variables in functions
In the following example, we would like to demonstrate how to use global values inside a function body:
def f (): print ( s ) s = “I love Paris in the summer.!” f ()
Output:
I love Paris in the summer!
Before the function f() is called, the variable s is defined as the string "I love Paris in the summer!" The body of f() consists only of the "print(s)" statement. Since there is no local variable s, i.e. no assignment to s, the value of the global variable s will be used. So the output will be the string "I love Paris in the summer!" . The question is, what happens if we change the value of s in the function f()? Does it affect the global variables as well? We tested this in the following piece of code:
def f (): s = "I love London!" printable( s ) s = “I love Paris.!” f () printable( s )
Output:
I love London!
I love Paris!
What if we combine the first example with the second, where we first access s using the print() function, hoping to get the global value, and then assign a new value to it? Assigning a value to it means - as we said before - creating a local variable s. Thus, we would treat s as a global variable and a local variable in the same scope, i.e., the body of the function. Fortunately, Python does not allow this ambiguity. Therefore, it will raise an error, as we see in the following example:
def f (): print ( s ) s = “I love London.!” printable( s ) s = “I love Paris.!” f ()
Output:
UnboundLocalError Traceback (most recent call last)
<ipython-input-3-d7a23bc83c27> in <module>
5
6 s = "I love Paris!"
----> 7 f ( )
<ipython-input-3-d7a23bc83c27> in f ()
1 def f ( ) :
----> 2 print ( s )
3 s = "I
Love London!" 4 Print( s )
5
UnboundLocalError: local variable "s" was referenced before the assignment.
Variables cannot be both local and global within a function. Because it assigns a value to s inside f(), Python decides that we need a local variable, so the first print statement before the definition of s throws the error message above. Any variable that is changed or created inside a function is a local variable if it is not declared as a global variable. To tell Python that we want to use global variables, we must explicitly say so with the keyword "global," as shown in the following example:
def f (): global s print ( s ) s = "Spring only, but London is great too!" printable( s ) s = "I'm looking for courses in Paris!" f () printable( s )
Output:
I'm looking for courses in Paris!
Only in the spring, but London is great too!
Only in the spring, but London is great too!
Local variables of a function cannot be accessed externally after the function call has completed. This is a continuation of the previous example:
def f (): s = "I am not known globally." printable( s ) f () printable( s )
Output:
I'm globally unknown.
Only in the spring, but London is great too!
The following example shows a wild combination of local and global variables and function arguments:
def foo ( x , y ): security situation a a = 42 x , y = y , x b = 33 b = 17 c = 100 printable( a , b , x , y ) a , b , x , y = 1 , 15 , 3 , 4 foo ( 17 , 4 ) printable( a , b , x , y )
Output:
42 17 4 17
42 15 3 4
Global variables in nested functions
We will now examine what happens if we use the global keyword in a nested function. The following example shows the use of the variable "city" in various scopes:
def f (): city = "Hamburg" def g (): global city city = "Geneva" print ( "Pre-call g:" + city ) print ( "Now call g:" ) g () print ( "Post-call g: " + municipalities) f () print ( "The value of the main city:" + city )
Output:
Before calling g:burger
Now call g:
Call after g: Hamburg
Principal urban value: Geneva
We can see that the global statement in the nested function g does not affect the variable 'city' in the function f, i.e. it keeps its value 'Hamburg'. We can also deduce from this example that there is a variable 'city' in the module namespace with the value 'Geneva' after the call to f(). This means that the global keyword in a nested function does not affect the namespace of its enclosing namespace! This is consistent with what we found in the previous chapter: a variable defined inside a function is local unless it is explicitly labeled as a global variable. In other words, we can reference a variable name in any closed scope, but we can only rebind it in a local scope by assignment, or in the module's global scope by using a global declaration. We also need a way to access variables in other scopes. The way to do this is with non-local definitions, which we will explain in the next chapter.
nonlocal variable
Python 3 introduces non-local variables as a new kind of variable. Non-local variables have a lot in common with global variables. One difference from global variables is that it is not possible to change module-scoped variables, i.e., variables that are not defined inside a function, by using non-local statements. We demonstrate this in the following two examples:
def f (): the (whole) world municipalities printable( city ) city = "Frankfurt." f ()
Output:
Frankfurt (Germany)
The program is correct and returns "Frankfurt" as output. We will change "global" to "non-local" in the following program:
def f (): non-local municipalities printable( city ) city = "Frankfurt." f ()
Output:
file "<ipython-input-9-97bb311dfb80>", 2nd
Row Non-local city
^
Syntax error: non-local "city" binding not found
This indicates that non-local bindings can only be used inside nested functions. Non-local variables must be defined in closed function scopes. If a variable is not defined in a closed function scope, it cannot be defined in a nested scope. This is another difference from the "global" semantics.
def f (): city = "Munich" def g (): nonlocal city city = "Zurich" print ( "Pre-call g:" + city ) print ( "Now call g:" ) g () print ( "Post-call g: " + municipalities) city = "Stuttgart" f () print ( "'city' in main:" + city )
Output:
Before calling g: Munich
Now call g:
After dialing g: Zurich
Main "cities": Stuttgart
In the previous example, the variable 'city' was defined before g was called. If it had not been defined, we would have gotten an error:
high definition (photo, audio or television) ˚F (): #city = "Munich" high definition (photo, audio or television) g ^ (): parts of the country other than where one is city 城city = “Zurich, Switzerland” printable(“Before calling the facsimile:” + 城city) printable(“Call NowG:” ) g ^ () printable(“backward call g: " + city ) city = "Stuttgart" f () print ( "'city' in main:" + city )
Output:
File "<ipython-input-11-5417be93b6a6>" , page 4
Row Non-local city
^
Syntax error: non-local "city" binding not found
The program works fine - if we change "non-local" to "global", there is or is not a 'city = "Munich"' line in f -:
def f (): #city = "Munich" def g (): global city city = "Zurich" print ( "Before call g:" + city ) print ( "Calling g now:" ) g () print ( "After calling g:" )yell g: " + city ) city = "Stuttgart" f () print ( "'city' in main:" + city )
Output:
Before calling: Stuttgart
Now call g:
After dialing g: Zurich
Main "city": Zurich
There is one big difference, however: the value of the global x now changes!