Global and Local variables in Python

Global and Local variables in Python

A beginners perspective

Backstory

The main reason for writing about this topic came when I worked with python at my workplace. There came an instance while coding when The code I wrote worked, but It shouldn't have A typical developer moment. The problem looked like this -

Corrected-image-LinkedIN.jpg

To have a better understanding on why my code did worked, I had to explore the concept of global variables in python deeply. Hence forth, Here are my learnings.

Base definitions

Local Variable

In simple words Local variables "variables which can be accessed only inside the function in which they were defined in"

Global Variable

In simple words Global variables "variables which can be accessed throughout the code base"

Let's understand this with the help of a few examples

Example 1 -

def fun():
    print("== Inside fun ==")
    # Local variable
    a = 2
    print("The value of a is = ", a)
    print("== Outside fun ==")

# Driver Code
fun()

Output

== Inside fun ==
The value of a is =  2
== Outside fun ==

Example 2 -

def fun():
    print("== Inside fun ==")
    # Local variable
    a = 2
    print("The value of a is = ", a)
    print("== Outside fun ==")

# Driver Code
fun()
print(a)

Output

The value of a is =  2
== Outside fun ==
Traceback (most recent call last):
NameError: name 'a' is not defined

"a" is defined in the context of the function "fun" and is only accessible inside that context, Outside it gives a "variable not defined" error

Precedense order

What if there are two variables with same name but in different contexts, Which one will be given precedense?

Let's take a look at this case by case

Case 1 - Global variable accessed inside a function

def fun():
    print("== Inside fun ==")
    print("The value of a is = ", a)
    print("== Outside fun ==")

# Driver Code
a = 5
fun()

Output

== Inside fun ==
The value of a is =  5
== Outside fun ==
== In Global Context ==
The value of a is =  5

Variable "a" is a global variable, Hence it can be accessed anywhere in the code

Case 2 - Global and local variable with the same name

def fun():
    print("== Inside fun ==")
    # Local variable
    a = 2
    print("The value of a is = ", a)
    print("== Outside fun ==")

# Driver Code
# Global Variable
a = 5
fun()
print("== In Global Context ==")
print("The value of a is = ", a)

Output

== Inside fun ==
The value of a is =  2
== Outside fun ==
== In Global Context ==
The value of a is =  5

If there is a new definition of the variable with the same name, Then the local context is given precedence.

Altering the value of global variable

Concept - Re-Defination(as can be observed from Case 2 above) of global variable is allowed in local context, but for altering the value of the global variable, We would require the need of global keyword

The global keyword is used to modify the variable outside of the current scope.

Take a look at this code. Its trying to change the value of a global variable in a local context

def fun():
    print("== Inside fun ==")
    # adding one to the existing value
    a = a + 1
    print("The value of a is = ", a)
    print("== Outside fun ==")

# Driver Code
a = 5
fun()
print("== In Global Context ==")
print("The value of a is = ", a)

Output

== Inside fun ==
Traceback (most recent call last):
fun()
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment

As can be seen, We cannot just simply alter the value of the global variable from the existing one(In this case we tried adding one to the existing value)

Reason for the error - Python “assumes” that we want a local variable "a" due to the assignment to "a" inside the function "fun", When Its not able to find it inside the local context it throws an error

Using "global" variable

def fun():
    global a
    print("== Inside fun ==")
    # adding one to the existing value
    a = a + 1
    print("The value of a is = ", a)
    print("== Outside fun ==")

# Driver Code
a = 5
fun()
print("== In Global Context ==")
print("The value of a is = ", a)

Output

== Inside fun ==
The value of a is =  6
== Outside fun ==
== In Global Context ==
The value of a is =  6

Using the global keyword tells the python Interpreter that we want to utilize the global variable "a" in the local context.

How it gets rid of the Error local variable 'a' referenced before assignment? This time around python will look in the global context and finds the variable assignment there and allows its alteration in the local context.

An Example covering all use cases

# Uses global because there is no local 'a'
def fun1():
    print("== Inside fun1 ==")
    print("The value of a is = ", a)

# Variable 'a' is redefined as a local
def fun2():
    print("== Inside fun2 ==")
    a = 2
    print("The value of a is = ", a)

# Uses global keyword to modify global 'a'
def fun3():
    print("== Inside fun3 ==")
    global a
    a = 3
    print("The value of a is = ", a)

# Global scope
a = 8
print("== In Global Context, The value of a is - ", a)
fun1()
print("== (After fun1) In Global Context, The value of a is - ", a)
fun2()
print("== (After fun2) In Global Context, The value of a is - ", a)
fun3()
print("== (After fun3) In Global Context, The value of a is - ", a)

Output

== In Global Context, The value of a is -  8
== Inside fun1 ==
The value of a is =  8
== (After fun1) In Global Context, The value of a is -  8   
== Inside fun2 ==
The value of a is =  2
== (After fun2) In Global Context, The value of a is -  8   
== Inside fun3 ==
The value of a is =  3
== (After fun3) In Global Context, The value of a is -  3

Global variables, When imported to another file

Let's take a scenario where we have two python scripts namely script1 and script2 and their contents look like this (Both are under the same directorry)

script1.py

import script2
print("This is in Script 1")
# Accessing the global variable defined in Script 2
print("globalVariableInScript2 has value - ", script2.globalVariableInScript2)

script2.py

globalVariableInScript2 = 4
print("This is in script 2")

Here in this scenario we are trying to access a global variable defined in script2 via script1

Output of script1

This is in script 2
This is in script 1
globalVariableInScript2 has value -  4

Conclusion

These are all the learnings it took to know why my code worked. I hope you also got something to learn from reading it as much as I had while making it. Until next time, when I stumble upon a problem statement. Thanks for Reading 👋

Connect with me

If you read through the end, why not get connected? Here are my socials - Bhavuk's Social Profiles