Labs ICT
Pro Login

Scope

1 min read | Python Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Scope

Scope determines where a variable is accessible. Python follows the LEGB rule: Local, Enclosing, Global, Built-in.

Local vs Global

A variable defined inside a function is local. A variable defined outside is global.

x = 10

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

show()
print("Outside:", x)

The global Keyword

Use global to modify a global variable from inside a function.

counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)

Enclosing Scope (Closure)

Variables in an outer function are visible to an inner nested function.

def outer(msg):
    def inner():
        print(msg)
    return inner

hello = outer("Hello!")
hello()