Python Variable Scope

In Python, the scope of a variable refers to the region of the code where a variable is recognized and can be accessed. Understanding scope is essential to avoid errors when using variables across different parts of your code.



What You'll Learn

In this section, you will learn how variable scope works in Python. We'll discuss how Python determines the visibility and lifespan of variables based on their scope.


Understanding Variable Scope

There are three main types of scopes in Python: local, global, and nonlocal. Let’s take a closer look at each:

  • Local Scope: A variable declared inside a function is only accessible within that function.
  • Global Scope: A variable declared outside of all functions is accessible throughout the program.
  • Nonlocal Scope: A variable declared in a nested function is accessible by the inner function, but it’s not global.

When searching for a variable, Python looks in the following order: first the local scope, then the enclosing (nonlocal) scopes, and finally the global scope.


Example 1: Local Scope

Variables created inside a function are considered to be in the local scope. Here’s an example:

python
def my_function():
    x = 10  # Local variable
    print(x)

my_function()

How It Works:

  • x = 10: The variable x is defined inside the function my_function, making it local to that function.
  • print(x): Prints the value of x inside the function.

Output

10

Example 2: Global Scope

A variable declared outside any function is considered to be in the global scope, meaning it can be accessed from anywhere in the program.

python
x = 5  # Global variable

def my_function():
    print(x)

my_function()

How It Works:

  • x = 5: The variable x is declared outside the function, making it a global variable.
  • print(x): This function prints the value of the global variable x.

Output

5

Example 3: Nonlocal Scope

In Python, the nonlocal keyword allows you to assign a value to a variable in the nearest enclosing scope that is not global.

python
def outer_function():
    x = 10  # Variable in the outer function

    def inner_function():
        nonlocal x
        x = 20  # Modify the variable in the outer function
        print(x)

    inner_function()

outer_function()

How It Works:

  • x = 10: The variable x is defined in the outer function, making it nonlocal to the inner function.
  • nonlocal x: The nonlocal keyword allows us to modify the value of x from the outer function inside the inner function.
  • print(x): The inner function prints the modified value of x.

Output

20

Exercises

Try out the following exercises to practice understanding variable scope in Python.

1. Write a program that demonstrates local and global variables.
python
# Exercise 1: Local and Global Variables
# Define a global variable
x = 10

def my_function():
    # Define a local variable
    y = 5
    print(x)  # Access global variable
    print(y)  # Access local variable

my_function()

2. Write a program that uses the nonlocal keyword to modify a variable in the outer function.
python
# Exercise 2: Use nonlocal to modify variable in the outer function
def outer():
    x = 10

    def inner():
        nonlocal x
        x = 15
        print(x)

    inner()

outer()

*Tip: After completing an exercise, try to modify the code and explore how scope affects variables!


Frequently Asked Questions

What is variable scope in Python?

Variable scope determines where a variable can be accessed or modified in your Python program. It defines the visibility and lifetime of variables.


What are the different types of scopes in Python?

Python has three main types of scope: local, global, and nonlocal. Each defines where a variable is accessible within your code.


What is the LEGB rule in Python?

LEGB stands for Local, Enclosing, Global, and Built-in. It's the order Python follows to find a variable's value.


When should I use the global keyword?

Use the global keyword when you want to modify a global variable inside a function. Without it, Python treats the variable as local by default.


What does nonlocal mean in Python?

The nonlocal keyword is used in nested functions to modify a variable from the nearest enclosing scope (excluding global). It helps manage state across nested functions.



What's Next?

Next, you'll learn about recursive functions, which allow a function to call itself in order to solve problems that can be broken down into smaller, similar sub-problems. Understanding recursion is a powerful tool for solving complex problems in an elegant and efficient way.