Explain Global and Local Variables in Python
Global variables in Python are those declared outside of any function, allowing them to be accessed throughout the entire program. Conversely, local variables are defined within a function and are accessible only within that specific function. In simpler terms, local variables are confined to the function where they’re defined, while global variables can be accessed from any part of the program, including within functions.
Python Local Variables
In Python, local variables are the ones you set up within a function, and they’re exclusive to that function. You can’t use them outside that function. Let’s take a look at how you make and use local variables.
Example
def my_function():
# This is a local variable
message = "Hello, world!"
print(message)
# Calling the function
my_function()
Output
Hello, world!
Is it possible to use a local variable outside of its function?
If we attempt to use this local variable outside of the function, let’s find out what occurs.
Example
def my_function():
# This is a local variable
message = "Hello, world!"
print(message)
# Calling the function
my_function()
print(message)
Output
Hello, world!
Traceback (most recent call last):
ERROR!
NameError: name ‘message’ is not defined
Global Variables
Global variables in Python are those you define outside of any function, and you can access them from anywhere in your program, whether inside or outside of functions. Let’s learn how to make a global variable in Python.
Example
# Define a global variable outside of any function
global_var = "I am a global variable"
def my_function():
# Access the global variable inside the function
print("Inside the function:", global_var)
# Call the function
my_function()
# Access the global variable outside the function
print("Outside the function:", global_var)
Output
Inside the function: I am a global variable
Outside the function: I am a global variable
The variable ‘global_var’ is declared as a global variable and is utilized both within and outside the function.
Keep in mind: If there are no local variables, the value from the global variables will be used. However, it’s important to ensure that both the local and global variables have the same name.
What’s the purpose of using local and global variables in Python?
Now, let’s consider a scenario where a variable with the same name is defined both inside a function and globally in Python. The question then arises: will the local variable affect the global variable, or vice versa? And if we change the value of a variable inside the function, will it also affect the global variables? We’ll test this using the following code:
Example
If a variable with the same name is defined inside a function, it will only print the value assigned inside that function, ignoring the global value.
x = 10 # Global variable
def my_function():
x = 20 # Local variable with the same name as the global variable
print("Inside the function:", x)
# Call the function
my_function()
# Access the global variable outside the function
print("Outside the function:", x)
Output
Inside the function: 20
Outside the function: 10
Now, let’s explore what happens if we attempt to modify the value of a global variable from within a function. We’ll demonstrate this using the following example.
# Define a function that uses a global variable 's'
def f():
# Attempt to modify the global variable 's'
# This line will result in an UnboundLocalError because 's' is being used before being assigned locally
s += 'Hello World'
print("Inside Function:", s)
# Define a global variable 's'
s = "yes"
# Call the function
f()
Output
UnboundLocalError: cannot access local variable ‘s’ where it is not associated with a value
To make the program above work, we need to use the ‘global’ keyword in Python. Now, let’s understand what this ‘global’ keyword does.
Global Keyword
In Python, the global keyword is necessary within a function only when we intend to assign or modify a global variable. It’s not required for simply printing or accessing the global variable. Python automatically assumes that a variable assigned within a function is local to that function, hence attempting to modify it directly without declaring it as global leads to an error.
To inform Python that we want to use the global variable, we explicitly declare it with the global keyword. Here’s an example to illustrate this concept:
Example
# Define a global variable 's'
s = "I love Python"
# Define a function 'f' that attempts to modify the global variable
def f():
global s # Declare 's' as a global variable
s += " and AI" # Modify the global variable by appending ' and AI'
print("Inside Function:", s)
# Call the function
f()
# Access the global variable outside the function
print("Outside the function:", s)
Output
Inside Function: I love Python and AI
Outside the function: I love Python and AI
Conclusion
In Python, global variables are accessible throughout the entire program, while local variables are confined to the function where they’re defined. To modify a global variable within a function, the global keyword must be used. Understanding this distinction helps in writing clear and maintainable code.