Global And Local Variables In Python

Discover the key differences between global and local variables in Python, including scope, accessibility, and how to use them effectively in your code.

The global variables in Python are declared outside functions and can be accessed globally, while local variables are declared within functions and can only be used inside them. To modify a global variable inside a function, use the global keyword. This distinction allows for variable scope management, ensuring variables are used and altered where intended.

Python Local Variables

Python local variables are defined within the scope of a function and are only accessible within that function. These variables exist when the function is called and cease to exist once the function returns. Local variables help keep the global namespace clean and prevent unexpected modifications to data.

For instance, in the following code, x is a local variable within the function add_one.

def add_one(number):
    x = number + 1  # x is a local variable
    return x

print(add_one(4))

Output.

5

In this example, x is not accessible outside the add_one function, showcasing the encapsulated nature of local variables. This ensures that x can only influence operations within its local context, promoting code modularity and readability.

Python Global Variables

Python global variables are defined outside of any function and have a global scope, meaning they can be accessed and modified throughout the entire program. These variables are essential for sharing data between different functions without needing to pass them as parameters.

To declare a global variable, define it outside of all functions, for example.

x = "global variable"

def access_global_variable():
    print("Inside the function:", x)

access_global_variable()
print("Outside the function:", x)

Output.

Inside the function: global variable
Outside the function: global variable

If you need to modify a global variable within a function, use the global keyword before the variable name.

x = "global variable"

def modify_global_variable():
    global x
    x = "modified global variable"

modify_global_variable()
print(x)

Output.

modified global variable

This approach ensures that changes to the global variable are reflected throughout the entire program, enabling functions to share and update global data effectively.

Why Do We Use Local And Global Variables In Python?

We use local and global variables in Python to manage the scope and lifetime of variables, ensuring data encapsulation and reducing the risk of unintended modifications. Local variables, defined within functions, keep changes local to the function, enhancing code readability and preventing side effects outside the function. Global variables, accessible throughout the program, facilitate data sharing across different functions.

For instance, a global variable can be used to set a configuration value that multiple functions read.

config_value = "default"  # Global variable

def update_config(new_value):
    global config_value  # Declare the intention to use the global variable
    config_value = new_value  # Modify the global variable

def print_config():
    print(config_value)  # Access the global variable

print_config()  # Output: default
update_config("updated")
print_config()  # Output: updated

This code snippet demonstrates the use of global and local variables to maintain configurations and adapt behavior dynamically.

The Global Keyword

The global keyword in Python is essential for modifying global variables within a local scope, such as inside a function. It explicitly tells the Python interpreter that a variable is global, allowing you to update its value from within a function. This is crucial for maintaining state or data across the execution of your program.

For example, if you have a global variable counter and wish to increment it within a function, you would use the global keyword like this.

counter = 0

def increment_counter():
    global counter
    counter += 1

increment_counter()
print(counter)

Output.

1

This code effectively increments the global counter variable from within the increment_counter function, demonstrating how the global keyword bridges the scope between local and global variables.

Difference Between Local And Global Variables

The difference between local and global variables in Python pertains to their scope and accessibility. Local variables, defined within a function, are accessible only inside that function, limiting their scope to the function's body. Conversely, global variables are defined outside any function and can be accessed and modified throughout the entire program, making their scope global.

For instance, consider the following code snippet.

x = 5  # global variable

def modify_variables():
    y = 10  # local variable
    global x
    x = x + 1
    print("Inside function, local y =", y)
    print("Inside function, global x modified to =", x)

modify_variables()
print("Outside function, global x =", x)

Output.

Inside function, local y = 10
Inside function, global x modified to = 6
Outside function, global x = 6

This example demonstrates how a local variable y is accessible only within modify_variables, whereas the global variable x is accessible and modifiable both inside and outside the function, showcasing their fundamental difference in scope and accessibility.

You can also check these blogs:

  1. Global Keyword In Python