Python Scope


Scope in Python decides where a variable can be accessed. When you write code, different variables live in different parts of your program. Some variables can be used anywhere, while others exist only inside a function. Understanding scope helps you avoid errors, write cleaner programs, and control how data moves across different blocks of code.

In this tutorial, you will learn how scope works in Python, the types of scope, how functions interact with variables, and how to use global and nonlocal correctly with real examples.

What Is Scope?

Scope refers to the area of a program where a variable is recognised. When you create a variable, Python decides whether it is available everywhere or only inside a certain block.

If you try to use a variable outside its scope, Python will show an error. This is why understanding scope is important.

Types of Scope in Python

Python follows a rule called LEGB, which stands for:

  • Local

  • Enclosed

  • Global

  • Built-in

Each level decides where Python looks when you use a variable.

Local Scope

A variable created inside a function is part of the local scope. It can only be used inside that function.

Example:

def greet():
    message = "Hello from inside the function"
    print(message)

greet()
print(message)   # Error

Here, message exists only inside the function.

Global Scope

A variable created outside every function belongs to the global scope. It can be accessed from anywhere in the program.

Example:

name = "Aarohi"

def show():
    print(name)

show()
print(name)

Both statements work because name is global.

Local vs Global Variables

If a function has a variable with the same name as a global variable, Python treats them separately.

Example:

age = 20

def update():
    age = 25
    print("Inside:", age)

update()
print("Outside:", age)

The two age variables are not the same.

Changing Global Variables Inside a Function

To change a global variable inside a function, you must use the global keyword.

Example:

count = 0

def add():
    global count
    count += 1

add()
print(count)

Without global, Python creates a new local variable instead of changing the global one.

Enclosed Scope

Enclosed scope appears when you have a function inside another function. The inner function can access variables of the outer function.

Example:

def outer():
    city = "Delhi"

    def inner():
        print(city)

    inner()

The variable city belongs to the outer function but is still available inside the inner function.

Using nonlocal in Nested Functions

If you want the inner function to modify a variable of the outer function, use nonlocal.

Example:

def outer():
    total = 10

    def inner():
        nonlocal total
        total = 20

    inner()
    print(total)

outer()

nonlocal helps you update enclosed variables without creating a new one.

Built-in Scope

Python has many reserved words and built-in functions like:

  • len()

  • sum()

  • list

  • dict

These belong to the built-in scope, and you should avoid naming your variables the same.

Example:

list = 10       # Bad idea
print(list)

This shadows the built-in list type.

Variable Lifetime

The lifetime of a variable depends on its scope.

  • A local variable exists only while the function is running.

  • A global variable exists until the program ends.

Example:

def demo():
    x = 5
    print(x)

demo()
print(x)   # Error

The local variable disappears after the function finishes.

Real Life Example: Calculating Tax

Global variable:

tax_rate = 18

def calculate(amount):
    return amount + (amount * tax_rate / 100)

print(calculate(1000))

Nested functions using enclosed scope:

def bill():
    charge = 500

    def add_tax():
        return charge + (charge * 0.18)

    return add_tax()

print(bill())

Practical Examples

  1. Local Scope Example

def work():
    task = "Coding"
    print(task)
  1. Accessing Global Inside Function

team = "Developers"

def info():
    print(team)
  1. Local Overriding Global

speed = 50

def test():
    speed = 80
    print(speed)
  1. Using global

count = 0

def inc():
    global count
    count += 1
  1. Enclosed Scope

def outer():
    value = 10
    def inner():
        print(value)
    inner()
  1. Using nonlocal

def outer():
    x = "Hello"
    def inner():
        nonlocal x
        x = "Hi"
    inner()
    print(x)
  1. Nested Function Access

def container():
    total = 100
    def add():
        print(total)
    add()
  1. Avoid Shadowing Built-ins

sum = 10  # Avoid this
  1. Function Lifetime Example

def temp():
    t = 30
    print(t)
  1. Global for Shared Values

config = "Debug"

def mode():
    print(config)

Summary of the Tutorial

Scope controls where a variable can be used. Local scope belongs to functions, while global scope works everywhere. Enclosed scope handles variables inside nested functions, and built-in scope includes Python’s predefined keywords and functions. You can use global and nonlocal to update variables from different scopes. Understanding scope helps you write code that is organised, error-free, and easy to maintain.


Practice Questions

Q1. Write a Python program to create a function with a local variable and print it inside the function.

Q2. Write a Python program to declare a global variable and access it inside a function using the variable name directly.

Q3. Write a Python program to modify a global variable inside a function using the global keyword.

Q4. Write a Python program to try accessing a local variable outside its function and observe the error.

Q5. Write a Python program to create nested functions and use nonlocal to modify a variable from the outer function.

Q6. Write a Python program to use the same variable name in global and local scope and print both.

Q7. Write a Python program to override a built-in name like sum and observe the effect.

Q8. Write a Python program to build a calculator that updates a global result variable after each operation.

Q9. Write a Python program to use the same global variable in two different functions and modify its value.

Q10. Write a Python program to create a counter using a nested function that updates a nonlocal variable.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top