Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
Python

Scope of Variables in Python

Understand local, enclosing, global, and built-in scopes (LEGB rule).

Scope of Variables in Python — a practical guide to Python variable scope with clear examples you can reuse in real projects.

Python Tutorial Series (32/95). Prefer one article? Read the complete Python tutorial.

Short description

Names resolve using LEGB. Use `global`/`nonlocal` carefully when you must rebind outer names.

Scope demo

x = 'global'

def outer():
    x = 'enclosing'
    def inner():
        print(x)  # enclosing
    inner()

outer()
print(x)

Leave a reply

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