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.
variable = 'Variable has global scope' def Func(): print (variable, 'inside the function') Func() print (variable, 'outside the function')
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.
variable = 4 def Func(): variable = 2 + variable print variable Func()
Traceback (most recent call last): File "<string>", line 6, in <module> File "<string>", 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.
def Func(): variable = 4 variable = 2 + variable print variable Func()
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.
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()
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()”.