Global Variables

A global variable is a variable that is declared outside of any function and can be accessed and modified throughout the entire program. You can use the global keyword to modify a global variable inside a function.

Understanding Local vs. Global Variables

Variables in Python have a scope, which defines where they can be accessed. A local variable is one that is defined inside a function and is only accessible within that function. In contrast, a global variable is defined outside any function and can be accessed anywhere in the code.

Python
x = "global"  # Global variable

def my_function():
    y = "local"  # Local variable
    print(y)  # Output: local

my_function()
print(x)  # Output: global
print(y)  # Error: NameError: name "y" is not defined

In the above example, the variable y is local to my_function and cannot be accessed outside of it, while x is a global variable accessible from anywhere in the program.

Example of Modifying a Global Variable

Python
x = "global"

def my_function():
    global x
    x = "modified global"
    print(x)

my_function()  # Output: modified global
print(x)  # Output: modified global

Without the global keyword, a variable inside a function is local and only accessible within that function. The global keyword allows you to modify the global variable within a function.

Using Global Variables Carefully

While global variables can be useful, they should be used sparingly. Overusing global variables can make your code harder to understand and debug. Here are a few best practices:

When to Use Global Variables

There are specific scenarios where global variables are particularly useful: