Hackforge Academy

Category: python

The LEGB Lookup Order

Published on 27 Oct 2026

Explanation

Python resolves names through Local, Enclosing, Global, and Built-in scopes, in that order.

Code:

name = 'Global'
def show():
    name = 'Local'
    print(name)
show()
print(name)

Explanation

A name assigned inside a function is local by default and is not automatically available outside it.

Code:

def calculate():
    result = 100
    print(result)
calculate()

Explanation

A nested function can read names from its enclosing function when those names are not local to the inner function.

Code:

def outer():
    message = 'Outer'
    def inner(): print(message)
    inner()
outer()

Explanation

Functions can read module-level names. Assignment inside a function creates a local binding unless global is declared.

Code:

language = 'Python'
def show_language(): print(language)
show_language()

Explanation

Names such as len(), print(), and sum() are available through built-in scope. Avoid naming variables after built-ins.

Code:

def total(values): return sum(values)
print(total([10, 20, 30]))
print(len('Python'))

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community