Unlocking the Power of Variable Scopes in Python

Local Variables: The Function’s Private Realm

Variables declared within a function have a local scope, meaning they can only be accessed within that function. These variables are private to the function and cannot be accessed outside of it.


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

greet()  # Output: Hello, World!
print(message)  # Error: message is not defined

Going Global: Variables with Unlimited Access

In contrast, variables declared outside of a function or in global scope are known as global variables. These variables can be accessed from anywhere in the program, both inside and outside of functions.


message = "Hello, World!"

def greet():
    print(message)

greet()  # Output: Hello, World!
print(message)  # Output: Hello, World!

The Nonlocal Variable: A Nested Relationship

In Python, the nonlocal keyword is used within nested functions to indicate that a variable belongs to an enclosing function’s scope. This allows us to modify a variable from the outer function within the nested function, while keeping it distinct from global variables.


def outer():
    message = "Hello, World!"

    def inner():
        nonlocal message
        message = "Hello, Universe!"
        print(message)

    inner()
    print(message)

outer()  # Output: Hello, Universe!
         # Output: Hello, Universe!

Key Takeaways

  • Local variables are private to a function and cannot be accessed outside of it.
  • Global variables can be accessed from anywhere in the program.
  • Nonlocal variables allow modification of outer function variables within nested functions.

Further Reading

Leave a Reply