What is Scope in Python?

Scope refers to the area in a Python program where a variable is recognized and can be used. It tells us where in the code you can access a variable or a function.

In simple words: “Scope defines the visibility of variables in your program.”



Imagine your house has different rooms - your bedroom, kitchen, living room, and maybe a study. Some items belong to specific rooms (like your toothbrush in the bathroom), while others are shared throughout the house (like the WiFi password).



In Python, scope works similarly - it determines where in your code a variable can be "seen" and used. Understanding scope helps you write cleaner code and avoid confusing bugs!



Why is Scope Important?

Without scope, your code would get confused between different variables with the same name. It helps Python know which variable you’re talking about at any point in the program.



The LEGB Detective Story

Python follows a specific order when searching for variables, known as the LEGB Rule.

Think of Python as a detective searching for clues :


1. L – Local: First, look inside the current function.

2. E – Enclosing: Then check the outer (enclosing) function, if you're in a nested function.

3. G – Global: If not found, look at the global level (outside all functions).



L - Local Scope (The Bedroom) :

Variables created inside a function - they're private to that function.

def my_bedroom():
    secret_diary = "Today I learned Python!"  # Only exists in this function
    print(secret_diary)

my_bedroom()  # Works fine
# print(secret_diary)  # ❌ Error! Can't access from outside

Key Point :

Local variables are created when a function runs and destroyed when it ends.



E - Enclosing Scope (The House) :

Variables in outer functions that inner functions can access.

def house():
    wifi_password = "Python123"  # Available to all rooms in this house
    
    def living_room():
        print(f"WiFi password is: {wifi_password}")  # Can access it!
    
    def kitchen():
        print(f"Still remember: {wifi_password}")  # This too!
    
    living_room()
    kitchen()

house()


Real-world Example :

def create_calculator(operation):
    def calculator(a, b):
        if operation == "add":
            return a + b
        elif operation == "multiply":
            return a * b
    return calculator

add_calc = create_calculator("add")
print(add_calc(5, 3))  # 8 - operation remembered from enclosing scope!


G - Global Scope (The Neighborhood) :

Variables defined at the top level of your script - available everywhere.

neighborhood_name = "Pythonville"  # Global variable

def introduce_yourself():
    print(f"I live in {neighborhood_name}")

def give_directions():
    print(f"Welcome to {neighborhood_name}!")

introduce_yourself()  # I live in Pythonville
give_directions()     # Welcome to Pythonville!


Modifying Global Variables :

bank_account = 100  # Global

def spend_money(amount):
    global bank_account  # Tell Python we want to modify the global
    bank_account -= amount
    print(f"Spent ${amount}. Balance: ${bank_account}")

spend_money(20)  # Spent $20. Balance: $80
print(bank_account)  # 80 - global variable was modified!


B - Built-in Scope (The Government) :

Pre-installed Python functions and constants available everywhere.

# These are all built-in - no import needed!
numbers = [1, 2, 3, 4, 5]
print(len(numbers))    # len is built-in
print(max(numbers))    # max is built-in
print(type(numbers))   # type is built-in

# You can even override them (but don't!)
# len = "I broke len!"  # Don't do this!


Tips to Remember :



Summary

Python's scope system follows the LEGB rule :



Understanding scope helps you :