Scope

Scope

Scope refers to the region or area in your code where a variable is recognized and can be accessed or used.

🎯 4 Types of Variable Scope:

TypeDescription
LocalInside a function
EnclosingInside nested functions
GlobalOutside all functions (entire file)
Built-inPython’s reserved words/functions

✅ 1. Local Scope

A variable declared inside a function.

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

greet()
# print(name)  # ❌ Error: name is not accessible here

📌 name is only accessible inside the greet() function.

✅ 2. Global Scope

A variable declared outside all functions.

x = 10  # Global variable

def show():
    print("x =", x)

show()
print("x outside function =", x)
x = 10  # Global variable

def show():
    print("x =", x)

show()
print("x outside function =", x)

📌 x can be used everywhere in the program.

✅ 3. Enclosing Scope (for nested functions)

def outer():
    msg = "Hi"  # Enclosing variable
    def inner():
        print(msg)  # Accesses enclosing scope
    inner()

outer()

📌 The inner() function can access msg from the outer (enclosing) function.

✅ 4. Built-in Scope

Python has its own built-in functions and keywords like print(), len(), etc.

print(len("Hello"))  # Built-in functions

These are available everywhere in your code.

🧠 Remember: LEGB Rule

Python looks for a variable in the following order:

L → Local
E → Enclosing
G → Global
B → Built-in

✅ Summary

Scope TypeWhere it’s accessible
LocalOnly inside a function
GlobalEntire program
EnclosingInside nested functions
Built-inAlways available

    Leave a Reply

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