Home Course Roadmap
Home Functions Lesson 31
Lesson 31 · Functions 45–55 minutes Beginner

Python Scope

Learn how Python decides where variables can be accessed, how local and global variables work, and how the LEGB rule helps Python find names.

Functions Variable Scope Core Concept
0%
01

What You Will Learn

By the end of this lesson, you will understand how Python manages variable names and how scope affects the way functions access data.

  • Understand local and global scope.
  • Explain the LEGB name-resolution rule.
  • Work with nested functions and enclosing scope.
  • Understand the global keyword.
  • Understand the nonlocal keyword.
  • Avoid common variable-scope mistakes.
01

What Is Scope?

In Python, scope refers to the region of a program where a variable or name can be accessed.

A variable does not automatically exist everywhere in your program. Python determines where a name is available based on where it was created.

Think of scope as a boundary.

A variable created inside a function normally belongs to that function. Code outside the function cannot directly access it.

Python
def greet():
    name = "Ali"
    print(name)

greet()

# print(name)  # NameError
Output
Ali

The variable name exists inside greet(). It is therefore a local variable.

02

Why Scope Matters

Scope helps keep programs organized by controlling which parts of a program can access particular names.

Without scope, variables created for one task could accidentally interfere with variables used by another part of a program.

Good scope design

Use local variables whenever data only belongs to one function. This makes functions easier to understand, test, and reuse.

03

Local Scope

A variable created inside a function normally has local scope.

Local Scope
def calculate_total():
    price = 100
    tax = 15
    total = price + tax

    print(total)

calculate_total()
Output
115

The variables price, tax, and total belong to the function.

Local means function-level scope.

Once the function finishes, its local variables are no longer directly available from outside that function.

04

Global Scope

A variable created outside all functions belongs to the global scope of the module.

Global Variable
company = "PyLearn"

def show_company():
    print(company)

show_company()
print(company)
Output
PyLearn
PyLearn

A function can normally read a global variable if it does not define a local variable with the same name.

05

Local vs Global Variables

Same Name, Different Scope
name = "Global Ali"

def greet():
    name = "Local Ahmed"
    print(name)

greet()
print(name)
Output
Local Ahmed
Global Ali

The two variables have the same name but belong to different scopes.

Important idea

Creating name inside greet() does not replace the global name.

06

The LEGB Rule

When Python sees a variable name, it searches for that name using the LEGB rule.

LEGB means:

Local → Enclosing → Global → Built-in

1. Local

Python first looks inside the current function.

2. Enclosing

If the current function is nested inside another function, Python looks in the surrounding function.

3. Global

Python then checks the module-level global scope.

4. Built-in

Finally, Python checks names provided by Python itself, such as len(), print(), and sum().

LEGB Example
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)

    inner()

outer()
Output
local

Python finds the local variable first, so it stops searching there.

07

Enclosing Scope

Enclosing scope exists when one function is defined inside another function.

Enclosing Scope
def outer():
    message = "Hello from outer"

    def inner():
        print(message)

    inner()

outer()
Output
Hello from outer

inner() does not have its own message, so Python searches the enclosing outer() scope.

08

Built-in Scope

Python provides many built-in names that are available without importing a module.

Built-in Names
numbers = [10, 20, 30]

print(len(numbers))
print(sum(numbers))
print(max(numbers))
print(min(numbers))
Output
3
60
30
10

Functions such as len(), sum(), max(), and min() are built-in names.

Avoid shadowing built-ins

Do not unnecessarily create variables such as list, str, sum, or len.

09

Nested Functions

A function defined inside another function is called a nested function.

Nested Function
def calculator():

    def add(a, b):
        return a + b

    result = add(10, 5)
    print(result)

calculator()
Output
15

The add() function is only available inside calculator().

10

The global Keyword

By default, assigning a value to a variable inside a function creates a local variable.

The global keyword tells Python that the assignment should modify the module-level variable.

Using global
counter = 0

def increase():
    global counter
    counter += 1

increase()
increase()
increase()

print(counter)
Output
3
Use global carefully

Although global is useful in some situations, excessive use can make programs harder to understand and maintain.

11

The nonlocal Keyword

The nonlocal keyword is used inside a nested function when you want to modify a variable belonging to the nearest enclosing function scope.

Using nonlocal
def counter():

    count = 0

    def increase():
        nonlocal count
        count += 1
        return count

    print(increase())
    print(increase())
    print(increase())

counter()
Output
1
2
3
global vs nonlocal

global targets module-level variables, while nonlocal targets a variable in an enclosing function.

12

Reading vs Modifying Variables

A function can usually read a global variable without using global.

Reading a Global
tax_rate = 0.15

def calculate_tax(price):
    return price * tax_rate

print(calculate_tax(100))
Output
15.0

But if you assign to that name inside the function, Python treats it as local unless you explicitly declare it as global.

Important distinction

Reading a global variable and assigning to a global variable are different operations.

13

Scope with Loops and Blocks

Python's if, for, and while statements do not create a separate local scope in the same way that functions do.

Loop Scope
for number in range(3):
    message = number

print(message)
Output
2

The variable message remains accessible after the loop because the loop does not create a function-level scope.

Remember

Functions create local scopes. Ordinary if, for, and while blocks do not work the same way.

14

Function Parameters and Scope

Function parameters are local variables belonging to the function call.

Parameters Are Local
def greet(name):
    message = f"Hello, {name}"
    print(message)

greet("Ali")

# print(name)  # NameError

The parameter name exists within the function's local scope.

This helps functions safely work with their own inputs without automatically creating global variables.

15

Real-World Examples

Example 1 — Application Configuration

Configuration
APP_NAME = "PyLearn"
MAX_USERS = 100

def show_config():
    print(APP_NAME)
    print(MAX_USERS)

show_config()
Output
PyLearn
100

Example 2 — Sales Calculation

Local Processing
def calculate_sale(price, quantity):

    subtotal = price * quantity
    discount = subtotal * 0.10
    final_price = subtotal - discount

    return final_price

print(calculate_sale(2000, 3))
Output
5400.0

The calculation variables are local because they are only needed while the function performs its work.

Example 3 — Counter with Enclosing Scope

Closure Pattern
def create_counter():

    count = 0

    def increment():
        nonlocal count
        count += 1
        return count

    return increment


counter = create_counter()

print(counter())
print(counter())
print(counter())
Output
1
2
3

This is a practical example of how an inner function can remember and modify a value from its enclosing function.

16

Common Scope Mistakes

Mistake 1 — Expecting Local Variables Outside

Incorrect
def create_user():
    username = "Ali"

create_user()

print(username)

This causes a NameError because username belongs to the function's local scope.

Mistake 2 — Forgetting global

Problem
score = 0

def add_score():
    score += 10

add_score()

Python treats score as a local variable because the function assigns to it.

If modifying the module-level variable is genuinely intended, use global score.

Mistake 3 — Using Too Many Globals

Large programs become difficult to maintain when many functions depend on and modify shared global variables.

Better approach

Prefer function parameters, return values, objects, and well-designed data structures instead of relying heavily on global state.

Mistake 4 — Shadowing Built-in Names

Avoid This
list = [1, 2, 3]

print(list("Python"))

The variable named list hides Python's built-in list() function.

17

Practice Exercises

Try solving these exercises before looking for a solution.

Exercise 1 — Local Variable

Create a function called show_name() that creates a local variable named name and prints it.

Exercise 2 — Global Variable

Create a global variable called company. Write a function that prints it.

Exercise 3 — LEGB

Create nested functions containing variables with the same name. Predict which value Python prints.

Exercise 4 — global

Create a global counter and a function that increases it by one using global.

Exercise 5 — nonlocal

Create an outer function containing count = 0 and an inner function that increments it using nonlocal.

Exercise 6 — Scope with Loops

Create a for loop and define a variable inside it. Print the variable after the loop. Observe what happens.

Exercise 7 — Parameters

Write a function that accepts a user's name as a parameter and explain why the parameter has local scope.

18

Challenge — Smart Counter

Build a reusable counter using an enclosing variable and nonlocal.

Your Task

Create a function named create_counter().

It should return another function that increases the counter every time it is called.

The expected behavior is:

Expected Usage
counter = create_counter()

print(counter())
print(counter())
print(counter())
print(counter())
Expected Output
1
2
3
4
Think before coding

The inner function needs to modify a variable belonging to the outer function. Which keyword should you use?

19

Quick Quiz

1

What does scope describe?

2

What is the first letter in LEGB?

3

Where is a normal function variable created?

4

Which keyword allows a function to modify a global variable?

5

Which keyword modifies a variable in an enclosing function?

6

Which scope contains functions such as len() and print()?

7

Do ordinary for loops create a function-like local scope?

8

What is the recommended approach for most temporary function data?

20

Lesson Summary

Scope determines where Python variables and names can be accessed.

  • Local scope belongs to the current function.
  • Global scope belongs to the module-level environment.
  • Enclosing scope appears with nested functions.
  • Built-in scope contains Python's built-in names.
  • Python searches names using the LEGB rule.
  • global allows a function to modify a module-level variable.
  • nonlocal allows a nested function to modify a variable from an enclosing function.
  • Function parameters are local variables.
  • Ordinary if, for, and while blocks do not create function-like local scopes.
  • Prefer local variables and clear function interfaces instead of excessive global state.
Key takeaway

Understanding scope is essential for writing predictable Python functions. Once you understand LEGB, local variables, enclosing variables, and global variables, many previously confusing Python errors become much easier to understand.

You've finished Python Scope!

Mark this lesson complete when you are comfortable with local scope, global scope, LEGB, global, and nonlocal.