🌐 Scope & Modules

Scope & Modules: Scope is like a room's line of sight — a note left INSIDE the room is invisible from outside; a variable inside a function is just as unreachable from outside it

Scope is like a room's line of sight — a note left INSIDE the room is invisible from outside; a variable inside a function is just as unreachable from outside it. But the more interesting question runs backward: can a function reach OUT and touch a global variable? Write test_counter = 0, then test_counter += 1 inside a function, and Python SILENTLY treats it as a local variable and throws "referenced before assignment" — because any line that assigns to a name tells Python "this is now LOCAL," whether you meant it or not. The fix: add "global test_counter" as the function's first line, telling Python "no, I mean the one out in the outer room." Java doesn't even have this concept — instance/static fields are always explicitly declared, so Python's "assignment makes it local by default" rule demands a genuinely different way of thinking.

Python uses the LEGB rule: Local → Enclosing → Global → Built-in. Java has a similar rule. The 'global' keyword allows writing to a global variable — but this pattern is generally avoided in practice.

Micro Lab: Python coding practice

Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.

Step by Step: Python coding practice

Read inputs and data types

Complete the critical line with the smallest change

Run the code and compare expected output

If it fails, read traceback or assertion message

Make the result reusable for a test report

In Python's LEGB rule, what does 'E' stand for?

LEGB = Local, Enclosing, Global, Built-in. Python searches for variables in this order. Enclosing refers to the scope of outer functions in nested function definitions.

According to the LEGB rule in Python, if a variable is not found in the local scope, where does Python search for it next?

Python searches for variables in the LEGB order: Local, Enclosing, Global, and Built-in. If a variable is not found in the local scope, it is next searched for in the Enclosing (outer function) scope.