Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
global, and nonlocal ArchitectureIn programming, a variable is not permanently visible across every single line of a project. Where a variable is created determines where it can be accessed, read, or modified, and when it will be destroyed from memory. This visibility boundary is known as variable scope.
Scope protects code from accidental side-effects: a variable named count inside a helper function will never accidentally overwrite a count variable in another part of your application. To resolve names unambiguously, Python enforces a strict lookup hierarchy known as the LEGB Rule.
+-------------------------------------------------------------------------------+
| VARIABLE SCOPE REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------------+
1. LOCAL SCOPE (Personal Bedroom Locker):
- Your personal wristwatch kept in your bedroom drawer.
- Only you inside that specific room can pick it up.
- Once you leave and lock the room, nobody outside has access.
2. ENCLOSING SCOPE (The Joint Family Living Room):
- The family television in the shared hall.
- Children inside their respective bedrooms can see and hear it,
- but people outside the house on the street cannot.
3. GLOBAL SCOPE (Apartment Building Notice Board):
- The society notice board posted at the main entrance gate.
- Every resident across all flats in the building can read it.
4. BUILT-IN SCOPE (The Law of the Land / Constitution of India):
- Universal legal standards (like driving on the left side of the road).
- Applies universally to everyone everywhere across all states and cities.
+-------------------------------------------------------------------------------+Whenever Python references a variable name, it searches through four concentric scopes in strict outward order:
Variables assigned inside a function body. Created when the function is called, destroyed when the function exits.
Applies only to nested functions. Variables in the outer function's scope that are accessible by an inner function.
Variables declared at the top-level indentation of the script/module or explicitly flagged via the global keyword.
Pre-loaded Python names: print, len, int, str, ValueError, True, False.
Output:
Notice how each function resolved its own x locally without clobbering the outer variables. This phenomenon is called variable shadowing.
Functions can read global variables freely:
However, if you attempt to assign/modify a variable inside a function, Python treats it as a brand-new local variable by default:
Output:
global Keyword: Explicit Global MutationIf you genuinely need to modify a top-level global variable from inside a function, you must declare it using the global keyword:
Output:
global keyword sparingly. Overusing global variables creates "hidden dependencies" where functions mutate state unpredictably, making debugging extremely difficult. In professional software, prefer passing parameters and returning updated values!nonlocal Keyword: Nested ClosuresWhen a function is nested inside another function, modifying the outer function's variable requires the nonlocal keyword (introduced in Python 3):
Output:
UnboundLocalErrorA classic Python bug occurs when you read and assign to a variable in the same function without declaring global:
The Fix: Add global counter at the top of the function if mutation of the global variable is truly intended.
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
| DO pass variables into functions as arguments and return updated values. | DON'T rely on global variables to pass data between functions. |
DO use uppercase names for true global constants: TAX_RATE = 0.18. | DON'T shadow Python built-in names like list = [1, 2] or str = "abc". |
DO use nonlocal when creating stateful closures or factory functions. | DON'T confuse nonlocal (enclosing function) with global (top-level module). |
global variable_name.nonlocal variable_name.id, type, list, or max.return StatementIf a function computes a value but doesn't return it, Python returns None by default:
global KeywordReading a global variable is permitted, but assigning to it creates a local variable unless explicitly declared:
A. Global, Local, Enclosing, Built-in B. Local, Enclosing, Global, Built-in (LEGB) C. Built-in, Global, Enclosing, Local D. Local, Global, Enclosing, Built-in
A. 100 B. 50 C. None D. UnboundLocalError
A. global B. outer C. nonlocal D. parent
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value?A. Variable x is defined as a string instead of an integer B. A function references x before its local assignment line, causing Python to treat x as an uninitialized local variable C. Variable x exceeds system memory D. The variable is imported from an external C library
list = [10, 20] considered dangerous in Python?A. It causes an immediate compiler crash B. It overwrites the built-in list constructor, making subsequent calls like list("abc") raise a TypeError C. It permanently deletes the list class from Python's standard library on disk D. It consumes double memory
Build a cash vault synchronization engine for a regional bank network.
The bank manages two financial levels:
CENTRAL_RESERVE_INR = 50000000.0 (Rs 5 Crore in RBI Master Vault).Write a state-managed branch manager using nested functions and the nonlocal keyword: create_bank_branch(branch_name, initial_vault_cash)
branch_cash in enclosing scope.process_branch_transaction(transaction_type, amount):nonlocal to modify branch_cash."DEPOSIT", increase branch_cash."WITHDRAWAL", ensure branch has sufficient funds, then deduct.branch_cash, request an emergency cash infusion from CENTRAL_RESERVE_INR using the global keyword!In the next lesson, we will continue your Python learning journey with Project: Calculator (14: Functions).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Recursion | Positional-Only, Keyword-Only Arguments & Basic Type Hints |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.