Understanding Variable Scopes In Python

Understanding Variable Scopes In Python

Learn to understand the different types of variable scopes when defining a function in the python programming language.

Introduction

I believe you should know what variables are and how it's being used in python and any other programming language. However, if you are getting to know about this for the first time, I have succinctly broken down and explained each terminology in texts and code as examples so that you will fully understand the topic and apply it whenever you need to use it.

What are variables?

Variables are simply storage or containers for storing data values and they need to be defined before using them. A label is assigned to a specific location in memory, the location then stores the assigned value you want your program to remember for later use. The assignment operator ('=') is used to create the variable and assign it to the value. Here is an example below:

fruits = "apple", "Banana"
Score_points = [78, 75, 36]

Assigning an initial variable to a value is called initializing. The variable fruits was assigned to the string values of apple, banana and assigning the variable Score_points was assigned to integer values of 75, 75, 36

Scope of variables

A scope is a region of the program where it is accessible and not all variables can be accessed anywhere.

There are two main types of scopes/variables I will explain in this article:

  1. Local scope

  2. Global scope

Local variables

Local variables are that which are declared within the region/scope of a function and cannot be changed or accessed outside of that function.
For example in the code below, a function is defined and the sum of three integers is assigned to a variable that can only be accessed within it (local scope).

def Total_points():
    #local variable
    total = 78 + 75 + 36
    print('The total points is:', total)

#driver code
Total_points()

#Let's try to access outside the Total_points function
print(total)

Output

The total points is: 189
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
c:\Users\DAP&QA\Downloads\variable scope in python.ipynb Cell 7 in 
      7 Total_points()
      9 #Let's try to access outside the Total_points function
---> 10 print(total)

NameError: name 'total' is not defined

As shown in the above code, the variable total in the Total_points() function is local to the function's body. Accessing the variable inside the function yields the correct result, while attempting to access it outside of the function results in a NameError: name 'total' is not defined This error occurs because total is not accessible outside of the function due to its local scope. To resolve this, we can make the total variable a global variable by defining it outside the function's body, allowing it to be accessed and modified from anywhere in the program.

Global variables

A variable declared outside of a function, not specified to any function and can be used anywhere within the program is called a global scope. An example of a global scope is shown below:

#define a global variable
greeting = "Hello"

def fullname():
    #define a local variable
    fullname = "Elon Musk"
    print(greeting, fullname)

# Define a function that prints a greeting and a name passed as an argument
def newname(Enoch):
    print(greeting, Enoch) 

#call the functions
fullname()
newname("Enoch Adetunji")

Output

Hello Elon Musk
Hello Enoch Adetunji

In the above code, I defined a variable named greeting in a global scope, defined two functions one without an argument and the other with an argument named Enoch and called both functions.

Global keyword

There are various keywords in python which cannot be used for any other purpose in the program because of their specific functionality and the Global keyword is among. The global keyword is simply used to create a global variable in a local scope as the global keyword makes the variable global. An example of how the global keyword is used is shown below:

#the function changes the global variable 'name'
def fullname():
    global name
    print(name)
    name = "Enoch Adetunji"
    print(name)

#Global scope
name = ("My names are Enoch Adetunji")
fullname()
print(name)

Output

My names are Enoch Adetunji
Enoch Adetunji
Enoch Adetunji

Non-Local keyword

These are variables used in nested functions which do not have a defined scope. In other words their variables do not exist in a local and a global scope. The nonlocal keyword is used to create nonlocal variables. See example of a non-local variable below:

#outside function
def outer():
    third_position = ("7 points")

    #nested function
    def inner():      

        #declare nonlocal variable
        nonlocal third_position

        #assign variable to a message
        first_position = ("10 points")
        second_position = ("8 points")
        print('The first psoition scored', first_position)
        print('the second position scored', second_position)

    inner()
    print('The third_position scored', third_position)

outer()

Output:

The first psoition scored 10 points
the second position scored 8 points
The third_position scored 7 points

In the above, the inner() function is defined in the scope of the outer() function, which all together is a nested function.
Note: If the value of a nonlocal variable is changed, the changes will be seen in the local variable.

Conclusion

You've been able to identify and understand what a variable scope is, the types of variables and how to use a global and nonlocal keyword/variable when writing functions in a python programming language.

References