Python Variable Scope: Local, Global and Nonlocal

Introduction: Variable Scope in Python

A variable stores a value that a program can use later. But when a program has many functions and variables, a question can arise: where can each variable be accessed?

For example, a variable created inside one function may not be available in another function. Without clear rules about where variables can be accessed, it would be difficult to control which parts of a program can use them.

Python solves this problem by defining a scope for variables. Scope determines where a variable can be accessed in a program.

What Is Variable Scope?

Definition: Variable scope is the part of a Python program where a variable can be accessed and used.

Let’s see how Python determines the scope of a variable and how variables from different scopes can be accessed.

Why Variable Scope Matters

Scope prevents variables in one part of a program from interfering with variables in another part. It also determines which variable Python uses when different scopes contain variables with the same name.

For example, a function can use a local variable named message without changing a global variable with the same name.

The two main types discussed when learning Python variable scope are local variables and global variables. Understanding where these variables are created and where they can be accessed makes it easier to understand how Python handles scope.

Local and Global Variables

Python commonly uses local and global variables depending on where a variable is created.

  • Local variable: A variable created inside a function and normally accessible only within that function.
  • Global variable: A variable created outside functions and generally accessible throughout its module.
name = "Alice"    # Global variable

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

greet()


# Output:
Hello Alice

Explanation: The name variable is global because it is created outside the function. The message variable is local because it is created inside greet().

For detailed explanations, examples and common use cases, see their dedicated pages.

Related Scope Concepts

Some important variable scope concepts and differences are covered separately to avoid repeating the same explanations across multiple pages.

global and nonlocal Keywords

Python also provides the global and nonlocal keywords when a function needs to modify a variable outside its local scope.

global Keyword

The global keyword allows a function to modify a variable from the global scope.

count = 0

def increase():
    global count
    count += 1

increase()
print(count)


# Output:
1

Explanation: Here, global count allows increase() to modify the global count variable.

For a detailed explanation, see: Python global Keyword: Syntax, Uses, Examples and Common Mistakes

nonlocal Keyword

The nonlocal keyword allows a nested function to modify a variable from an enclosing function.

def outer():
    count = 0

    def increase():
        nonlocal count
        count += 1

    increase()
    print(count)

outer()


# Output:
1

Explanation: Here, nonlocal count allows increase() to modify the count variable belonging to outer().

For a detailed explanation, see: Python nonlocal Keyword: Syntax, Uses, Examples and Common Mistakes

Global vs Nonlocal Keywords

The global and nonlocal keywords are used to modify variables outside a function’s local scope, but they refer to different scopes. The differences between them are explained separately.

Global vs Nonlocal Keywords in Python

Common Variable Scope Mistakes

Here are some of the common mistakes that can occur when working with variable scope in Python.

  1. Using the Wrong Variable With the Same Name
  2. Expecting a Local Variable to Be Available Outside Its Function
  3. Changing a Global Variable When Only a Local Variable Was Intended
  4. Confusing global and nonlocal

1. Using the Wrong Variable With the Same Name

message = "Global"

def show_message():
    message = "Local"
    print(message)

show_message()


# Output:
Local

Explanation: The local message takes priority inside show_message(). The global variable is not changed.

2. Expecting a Local Variable to Be Available Outside Its Function

def create_message():
    message = "Hello"
    print(message)

create_message()


# Output:
Hello

Explanation: The message variable belongs to create_message() and is available only within that function.

3. Changing a Global Variable When Only a Local Variable Was Intended

count = 10

def update_count():
    count = 20
    print(count)

update_count()
print(count)


# Output:
20
10

Explanation: The assignment creates a local count inside the function. The global count remains unchanged.

4. Confusing global and nonlocal

count = 0

def outer():
    count = 10

    def change():
        nonlocal count
        count = 20

    change()
    print(count)

outer()
print(count)


# Output:
20
0

Explanation: The nonlocal keyword changes the variable in the enclosing outer() function, not the global count.

For error-specific examples and detailed explanations, see the dedicated local variable, global, and nonlocal tutorials.

Practical Examples of Variable Scope

The following examples make it easier to understand how variable scope in Python works.

Example 1: Keeping Temporary Data Inside a Function

def calculate_total():
    price = 500
    tax = 50
    total = price + tax
    return total

print(calculate_total())


# Output:
550

Explanation: The price, tax, and total variables are local to calculate_total(). They are used only while calculating the result and do not interfere with variables elsewhere in the program.

Example 2: Using the Same Variable Name for Different Tasks

def calculate_area():
    result = 50 * 20
    print("Area:", result)

def calculate_price():
    result = 100 * 5
    print("Price:", result)

calculate_area()
calculate_price()


# Output:
Area: 1000
Price: 500

Explanation: Both functions use a variable named result, but each function has its own local result. The variables do not interfere with each other.

Example 3: Sharing a Program Setting

app_name = "Student Portal"

def show_header():
    print(app_name)

def show_footer():
    print("Welcome to", app_name)

show_header()
show_footer()


# Output:
Student Portal
Welcome to Student Portal

Explanation: The app_name variable is created outside the functions, so both functions can access it. This can be useful for a value that is shared across different parts of a program.

Example 4: Keeping State Inside a Function

def create_score():
    score = 0

    def add_points(points):
        nonlocal score
        score += points
        return score

    return add_points

add_score = create_score()

print(add_score(10))
print(add_score(20))
print(add_score(5))

# Output:
10
30
35

Explanation: The score variable belongs to the enclosing create_score() function. The nested add_points() function uses nonlocal to update the same value across multiple calls.

These examples show how Python scope can keep temporary data local, allow functions to use the same variable names safely, share common settings, and preserve state between function calls.

Best Practices for Variable Scope

Here are some simple practices for keeping variable scope in Python clear and manageable.

  • Keep variables local when only one function needs them.
  • Use global variables only when shared state is genuinely needed.
  • Use global only when a function must modify a global variable.
  • Use nonlocal when a nested function must modify a variable from an enclosing function.

Key Takeaways: Variable Scope

Here are the main points to remember about variable scope in Python.

  • Scope determines where a variable can be accessed.
  • Variables created inside functions normally belong to local scope.
  • Variables created outside functions normally belong to global scope.
  • Python provides global and nonlocal for specific scope-related situations.
  • Understanding scope helps prevent variable-access and assignment errors.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top