In this lesson, we will learn about Python’s global, local, and nonlocal variables, based on their scope and how to utilize them.
A variable’s scope is the area in which we may find it and, if necessary, access it. There are three types of Python variables based on their scope.
Let’s see all the variables in detail below.
A global variable in Python is declared outside the function or in the global scope, indicating whether you can access a global variable from within the function or not.
Let’s look at a Python example of constructing a global variable.
Example
variable = 'Variable has global scope' def Func(): print (variable, 'inside the function') Func() print (variable, 'outside the function')
Output
Variable has global scope inside the function Variable has global scope outside the function
In the code above, we create a global variable and define a Func () to print the global variable. Finally, we execute the Func(), which prints the variable’s value.
Example
variable = 4 def Func(): variable = 2 + variable print variable Func()
Output
Traceback (most recent call last): File "", line 6, in File " ", line 3, in Func UnboundLocalError: local variable 'variable' referenced before assignment
Because the variable is not defined inside Func() and Python regards’ variable’ as a local variable, the output contains an error ().
We employ the global keyword to make this function. We will find out in a later section.
A local variable is declared within the function’s body or local scope.
We attempted to access a local variable, ‘variable’, in the global scope, but the local variable only operates within the Func() or local scope; hence the output indicates an error.
Let’s look at an example of creating a local variable in Python.
Example
def Func(): variable = 4 variable = 2 + variable print variable Func()
Output
6
Nonlocal variables are used in nested functions with an undefined local scope, indicating that the variable cannot be local and global in scope. Let’s look at a Python usage example for a nonlocal variable.
To make nonlocal variables, we employ nonlocal keywords.
Example
def outerFunction(): var = "local function" def innerFunction(): nonlocal var var = "nonlocal function" print(var,"accessible from inner the function") innerFunction() print(var,"accessible from outer the function") outerFunction()
Output
nonlocal function accessible from inner the function nonlocal function accessible from outer the function
When we modify the value of a nonlocal variable, the local variable also changes. Like in the above example, when var is declared as nonlocal, and its var’s value is changed to “nonlocal function” inside the function, it prints “nonlocal function accessible from inner function”. Although, its value was different from “innerfunction()”.