Local and Global Variables

Learn how local and global variables work, how to use the global keyword, and the best practices for managing variable scope.

Loading...
Local and Global Variables

Local Variables

A local variable is defined inside a function and can only be used within that function.

It is created when the function is called and is destroyed once the function finishes execution.

Example:

def my_function():
    y = 5  # Local variable
    print(y)
 
my_function()
print(y)  # This will cause an error because 'y' is not accessible outside the function.
 

Output:

5
NameError: name 'y' is not defined

Global Variables

A global variable is declared outside of all functions and can be accessed from any function within the code.

Example:

x = 10  # Global variable
 
def my_function():
    print(x)  # Accessing the global variable inside the function
 
my_function()
print(x)  # Accessing the global variable outside the function
 

Output:

10
10
 

The global Keyword

The global keyword is used inside a function to indicate that a variable is defined in the global scope, allowing the function to modify its value.

Example:

x = 10  # Global variable
 
def my_function():
    global x
    x = 5  # Modifying the global variable
    print(x)
 
my_function()
print(x)  # The value of 'x' is now changed globally
 

Output:

5
5
 

Global Variables Without global

If you attempt to modify a global variable inside a function without using the global keyword, Python will treat it as a local variable, leading to an error.

Example:

x = 10
 
def my_function():
    x = x + 5  # This will cause an error because 'x' is treated as a local variable
    print(x)
 
my_function()
 

Error:

UnboundLocalError: local variable 'x' referenced before assignment
 

Summary Table

Type Defined In Accessible In Keyword Needed to Modify
Local Inside function Only inside that function No
Global Outside function Inside any function Yes (global)

Good Practices

  1. Limit the use of global variables: Overusing them can make your code harder to debug and maintain.
  2. Prefer passing arguments: Instead of modifying global variables, pass variables as arguments to functions.
  3. Encapsulation: Keep variables localized to where they are needed to avoid unintended side effects.

Support my work!