Global vs Local Scope & global Keyword Tracing (083)

⚡ Direct Answer & Key Takeaway

Python resolves variable names using the LEGB rule: Local, Enclosing, Global, and Built-in. Inside a function, reading a global variable works automatically if no local variable shares that name. However, assigning to a variable anywhere inside a function marks that name as strictly local for the entire function body, raising UnboundLocalError if read before assignment. To modify a module-level variable inside a function, declare global var_name before referencing or reassigning it.

1. Applying Python's LEGB Scope Resolution Rule

When Python executes an expression inside a function, it searches four nested namespaces in strict order: Local (names defined inside the current function), Enclosing (names in outer wrapper functions for nested definitions), Global (top-level module variables), and Built-in (predefined names like len, sum, and max). A variable assigned at the top level of a script lives in the global namespace for the entire file's lifetime. Conversely, a variable assigned inside a def block—including function parameters—exists only in that function's local frame and is destroyed when the function returns. If a local variable uses the same identifier as a global variable, the local binding shadows the global one inside that function without altering the global value outside. CBSE 083 papers routinely pair identically named global and local variables to verify whether students trace each function frame separately.

  • LEGB stands for Local -> Enclosing -> Global -> Built-in name resolution order.
  • Parameters and variables assigned inside def belong strictly to the local frame.
  • Local variables shadow identically named globals without changing the global value.

2. How the global Keyword Enables Rebinding

Reading a global variable inside a function requires no special declaration, yet trying to increment it with count += 1 triggers an UnboundLocalError. Why? Python determines variable scope at compile time, not line by line during execution. Because count += 1 contains an assignment to count, Python classifies count as local across the entire function. When Python evaluates the right-hand side count + 1 before any local value is bound, it fails immediately. Adding global count at the start of the function overrides this compile-time classification and binds every reference and assignment to the module-level variable. You can even create a brand-new global variable from inside a function using global new_var, provided the function executes before any external code reads new_var. Note that mutating a global list via items.append(5) does not require global because it modifies the object rather than rebinding the variable name.

  • Python classifies a name as local at compile time if it is assigned anywhere in the function.
  • Declare global var1, var2 at the top of the function before reading or writing them.
  • In-place mutation of a global list (lst.append(1)) works without the global keyword.

3. Step-by-Step Dry Run Table Method for Board Questions

To score full marks on multi-function CBSE 083 output-tracing questions, draw a two-column dry-run table separating Global Scope from each Function Local Frame. Before executing the first line, list every top-level variable and function definition in the Global column. Whenever a function call starts, open a fresh Local column listing its parameters and any global declarations. If a variable is declared global inside that function, draw an arrow or write directly into the Global column instead of creating a local slot. If a variable is assigned without global, record it strictly in the Local column and discard that column as soon as the function hits return or finishes. Watch carefully for default parameter evaluations, which read global values once at def time, and for print statements executed both inside and after the function call.

  • Separate Global variables and Local frames in a two-column dry-run table on rough sheets.
  • Discard local variables immediately once a function returns or ends.
  • Check whether default argument values captured a global variable earlier at def time.

4. Tracing Global vs Local Variables and the global Keyword

points = 50
bonus = 10

def update_local(val):
    points = val + bonus  # Local 'points' shadows global; reads global 'bonus'
    print("Inside update_local:", points)

def update_global(step):
    global points         # Binds 'points' directly to module-level variable
    points += step
    bonus = 25            # Local 'bonus' only
    print("Inside update_global:", points, bonus)

print("Start:", points, bonus)
update_local(30)
print("After update_local:", points, bonus)
update_global(15)
print("End:", points, bonus)

Verified Console / Dry-Run Output:

Start: 50 10
Inside update_local: 40
After update_local: 50 10
Inside update_global: 65 25
End: 65 10

5. Python Scope Behaviour With and Without the global Keyword

Scenario Inside Functionglobal Declared?Result in PythonImpact on Module Global
print(x) onlyNoReads global x via LEGBGlobal x remains unchanged
x = 99NoCreates new local x shadowing globalGlobal x remains unchanged
x = x + 1NoRaises UnboundLocalErrorExecution aborts before updating global
x = x + 1Yes (global x)Reads and rebinds module-level xGlobal x updates to new value
items.append(5) on global listNoMutates shared list object in placeGlobal list reflects appended item
🎯 1-on-1 Live Mentorship & Free Study Kit

Crack Scope Tracing Questions in a Free 1:1 Practice Pod

Turn tricky LEGB scope traces into guaranteed board marks with 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 practice session to walk through past-year CBSE 083 trace tables.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing count += 1 inside a function without global count, causing UnboundLocalError.
  • Avoid Mistake: Assuming assigning a local variable with the same name updates the global variable automatically.
  • Avoid Mistake: Placing global x after already reading or assigning x inside the same function (raises SyntaxError).
  • Avoid Mistake: Forgetting that function parameters are always local variables and cannot be listed in a global statement.
  • Examiner / Mentor Tip: Always check for a hidden assignment (= or +=) later in the function before assuming a read accesses a global variable.
  • Examiner / Mentor Tip: When asked the difference between local and global scope in viva, mention lifetime as well as visibility.
  • Examiner / Mentor Tip: Write out each print() line in exact execution order—never jump straight to the final print statement.

7. Interactive Concept Check Quiz

Question: What does the following CBSE-style snippet print?\nx, y = 5, 10\ndef change():\n global x\n x = x + y\n y = 20\nchange()\nprint(x, y)

8. Frequently Asked Questions

Why does x += 1 fail inside a function even when x is defined globally?
Python scans the entire function at compile time. Because x += 1 assigns to x, Python treats x as local throughout the function. Reading x before it gets a local value triggers UnboundLocalError instead of falling back to the global x.
Do I need the global keyword just to print or read a global variable?
No. Simply reading or printing a global variable works via the Global step of LEGB lookup, as long as the function never assigns to that variable name locally.
Can the global keyword create a brand-new global variable from inside a function?
Yes. Calling global new_total inside a function and assigning new_total = 100 inserts new_total into the module's global namespace once that function executes.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class