Python’s Global, Local, and Nonlocal Variables

In Python, variables have different scopes, which define where they can be accessed or modified. The three main types of variable scopes are:

  • Local Variables: Defined inside a function and accessible only within that function.
  • Global Variables: Defined outside any function and accessible throughout the script.
  • Nonlocal Variables: Used inside nested functions to modify variables from the enclosing function.

In this article, we will explore each of these variable types in detail with examples to help you understand them better.

Local Variables in Python

A local variable is declared inside a function and can be accessed only within that function. It is created when the function is called and destroyed once the function execution is completed.

Example:

def greet():
    message = "Hello, World!"  # Local variable
    print(message)

greet()
# print(message)  # This will raise an error because 'message' is not accessible outside the function.

Explanation:

  • The variable message is defined inside the greet() function.
  • It cannot be accessed outside the function.
  • Trying to print message outside the function results in an error.

Global Variables in Python

A global variable is declared outside any function and can be accessed throughout the script. However, modifying a global variable inside a function requires using the global keyword.

Example:

x = 10  # Global variable

def display():
    print("Value of x inside function:", x)

display()
print("Value of x outside function:", x)

Explanation:

  • x is a global variable, so it can be accessed both inside and outside the function display().
  • Since we are only reading the variable inside the function, it works fine.

Modifying a Global Variable Inside a Function

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

x = 10

def change_x():
    x = 20  # This creates a new local variable, doesn't modify the global x
    print("Inside function x:", x)

change_x()
print("Outside function x:", x)

To modify a global variable inside a function, we’ve to use the global keyword:

x = 10

def change_x():
    global x
    x = 20  # Modifies the global x
    print("Inside function x:", x)

change_x()
print("Outside function x:", x)

Nonlocal Variables in Python

A nonlocal variable is used inside a nested function and allows modification of a variable from the enclosing (outer) function.

Example:

def outer_function():
    a = "Hello"
    
    def inner_function():
        nonlocal a  # Refers to 'a' from outer_function
        a = "Hi"
    
    inner_function()
    print("Outer function a:", a)

outer_function() # Output: Outer function a: Hi

Explanation:

  • a is a variable in outer_function.
  • The inner_function tries to modify a, so we use the nonlocal keyword.
  • Without nonlocal, Python would treat a inside inner_function as a new local variable, leaving the outer a unchanged.

Differences Between Global, Local, and Nonlocal Variables

FeatureLocal VariableGlobal VariableNonlocal Variable
ScopeInside the function onlyAccessible anywhere in the scriptInside a nested function, modifies outer function variable
Declared UsingDirect assignment inside a functionDefined outside all functions, modified using globalDeclared inside a nested function using nonlocal
Accessed Outside Function?NoYesNo (only affects enclosing function)

Summary

What we learned?

  • Local variables exist inside a function and cannot be accessed outside it.
  • Global variables exist throughout the script, but modifying them inside a function requires the global keyword.
  • Nonlocal variables allow modifying a variable from an enclosing function using the nonlocal keyword.

We learned the concept of variable scoping in this article. It helps to write better python programs.

Tips: Always use the appropriate variable scope to avoid unintended bugs and improve code readability!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 205