Extra 5% OFF Use Code: OL05
Free Shipping over β‚Ή999

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.

    Need Help?