Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 05 / Topic 4 of 9

Scope: local, global and LEGB

A variable made inside a function is local. It disappears when the function ends. When Python looks up a name, it checks in this order (LEGB):

Letter Scope Example
L Local variable inside the current function
E Enclosing variable in an outer function (nested functions)
G Global variable at the top level of the file
B Built-in print, len, sum ...

Real-world example: a shop's GST rate is global; the bill amount is local.

GST_RATE = 0.18                  # global

def price_with_gst(amount):
    tax = amount * GST_RATE      # tax is local, GST_RATE is read from global
    return amount + tax

print(price_with_gst(100))       # 118.0
# print(tax) -> NameError: name 'tax' is not defined

The global keyword (and why to avoid it)

To change a global variable inside a function you need global. It works, but it makes code hard to test and follow. Better: pass the value in and return the new value.

visits = 0

def count_visit_global():
    global visits
    visits += 1

count_visit_global()
print(visits)                    # 1

def count_visit(current):        # better: no hidden changes
    return current + 1

visits = count_visit(visits)
print(visits)                    # 2

๐Ÿ” Going deeper: if a function assigns to a name anywhere, Python treats that name as local in the whole function. So count += 1 without global count fails with UnboundLocalError. To change a variable of an enclosing function, use nonlocal. See examples/03_mutable_default_and_scope.py for an enclosing (E) example.

Done here? The practice set for Part 5 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide