Python UnboundLocalError — Complete Fix Guide
Python UnboundLocalError — Complete Fix Guide 🔗
Python developers ka most confusing error — UnboundLocalError. Variable scope issues, global vs local variables, function shadowing — sab reasons cover karenge with solutions. Real employee data examples, debugging tips, aur interview questions ke saath. Data Insights par.
📑 Is Blog Mein Kya Sikhenge:
- 🟢 Basic: UnboundLocalError kya hai, kab aati hai
- 🟡 Medium: Common Causes — global variable shadowing, conditional assignment
- 🔴 Advanced: global keyword, nonlocal keyword, closures
- 🛠️ Solutions: Parameters, return values, class attributes
- 🔍 Debugging: Kaise trace aur prevent karo
- 💬 Interview: Top asked questions
1. UnboundLocalError — Kya Hai? 🟢
📘 Definition: UnboundLocalError Python ka built-in exception hai jo tab raise hoti hai jab tum function ke andar kisi variable ko USE karte ho jo ABHI TAK ASSIGN nahi hui, lekin same function mein LATER assign hoti hai. Ye NameError ki subclass hai. Ye error confusing hai kyunki lagta hai variable exist karti hai (global), lekin Python function scope mein use karte time confuse ho jaata hai.
🎯 Samjho Hinglish Mein: Socho tumhare ghar ke bahar ek "AARAV" naam ka board laga hai (global). Ab tumne room ke andar bhi likha "AARAV = new name". Python ne room enter karte hi dekh liya — "andar bhi AARAV naam use hoga later". Ab tum bolo "AARAV ko print karo" (uss line se pehle jaha assign kiya) — Python confuse — bahar wala use kare ya andar wala? Ye assume karta hai ki tum ANDAR waala chahte ho (kyunki andar assignment hai) — but abhi tak assign nahi hui — hence UnboundLocalError! Function scope Python ka trick concept hai.
📊 Sample Data (Employee Salary Calculator):
# Global company variables
company_name = "TechCorp"
total_employees = 5
average_salary = 66000
# Employee data
employees = [
{"name": "Aarav", "salary": 55000},
{"name": "Ishita", "salary": 72000},
{"name": "Kabir", "salary": 65000},
{"name": "Diya", "salary": 58000},
{"name": "Rohan", "salary": 80000}
]
def update_average():
print(f"Current average: ₹{average_salary}") # Read global
average_salary = sum(e["salary"] for e in employees) / total_employees
# ❌ UnboundLocalError!
# Python sees assignment below → treats as LOCAL variable
# But used BEFORE assignment → error!❌ Error Output:
update_average()
# ❌ ERROR OUTPUT:
# Traceback (most recent call last):
# File "salary.py", line 20, in <module>
# update_average()
# File "salary.py", line 14, in update_average
# print(f"Current average: ₹{average_salary}")
# UnboundLocalError: cannot access local variable 'average_salary'
# where it is not associated with a valuePython ke rules:
• Function mein assignment = variable LOCAL treated
• Read before assignment = UnboundLocalError
• Python scan karta hai POORI function pehle — assignments dekh ke local variables identify karta hai
• Even if global exists — assignment presence local banati hai
2. Cause 1 — Global Variable Shadowing 🟡
📘 Cause: Sabse common case — global variable exist karti hai, function ke andar SAME NAME ki variable assign karte ho, aur pehle usko READ karne ki koshish karte ho. Python confused ho jaata hai — assignment hai toh local samajh leta hai, but read before assign — error!
❌ Wrong Code (Error):
# ❌ Global variable
total_salary = 330000
def add_bonus():
print(f"Current total: ₹{total_salary}") # Read
total_salary = total_salary + 50000 # Assignment
print(f"After bonus: ₹{total_salary}")
add_bonus()
# ❌ UnboundLocalError: cannot access local variable 'total_salary'
# ❌ Another example — counter
counter = 0
def increment():
counter += 1 # ❌ UnboundLocalError
# Reason: counter += 1 is same as counter = counter + 1
# Assignment (=) makes it local, but read fails
# ❌ Employee count
employee_count = 5
def hire_employee():
print(f"Before: {employee_count} employees") # Read
employee_count = employee_count + 1 # Assignment
print(f"After: {employee_count} employees") # ❌ Error!✅ Fix Options:
# ✅ Solution 1: Use 'global' keyword
total_salary = 330000
def add_bonus():
global total_salary # Explicit: use global
print(f"Current total: ₹{total_salary}")
total_salary = total_salary + 50000
print(f"After bonus: ₹{total_salary}")
add_bonus() # ✅ Works!
print(f"Outside function: {total_salary}") # Also updated
# ✅ Solution 2: Pass as parameter (BEST!)
def add_bonus(current_total, bonus=50000):
print(f"Current: ₹{current_total}")
new_total = current_total + bonus
print(f"After: ₹{new_total}")
return new_total
total_salary = 330000
total_salary = add_bonus(total_salary) # ✅ Clean!
# ✅ Solution 3: Different variable name
total_salary = 330000
def calculate_new_total():
new_total = total_salary + 50000 # Different name
print(f"New total: ₹{new_total}")
return new_total
new_amount = calculate_new_total() # ✅ Works
# ✅ Solution 4: Return updated value
employee_count = 5
def hire_employee(current_count):
new_count = current_count + 1
print(f"Hired! Count: {current_count} → {new_count}")
return new_count
employee_count = hire_employee(employee_count)
# ✅ Explicit, clean, testable!3. Cause 2 — Conditional Assignment 🟡
📘 Cause: Variable ko if/else block ke andar assign kiya lekin condition FALSE ho toh assignment kabhi execute nahi hoti — variable "unbound" reh jaati hai. Python static analysis mein assignment DEKHTA hai but runtime pe skip ho sakti hai.
❌ Wrong Code (Error):
# ❌ Conditional assignment
def get_employee_bonus(salary):
if salary > 70000:
bonus = salary * 0.15
# No else clause!
return bonus # ❌ Error if salary <= 70000
print(get_employee_bonus(75000)) # ✅ Works: 11250.0
print(get_employee_bonus(55000)) # ❌ UnboundLocalError
# ❌ Nested conditions
def classify_employee(experience):
if experience > 5:
level = "Senior"
elif experience > 2:
level = "Mid"
# Missing: elif for <= 2 or else
return level # ❌ Error for experience <= 2
# ❌ Loop without match
def find_employee(emp_id, employees):
for emp in employees:
if emp["id"] == emp_id:
found = emp
return found # ❌ Error if no match found!✅ Fix Options:
# ✅ Solution 1: Initialize variable BEFORE condition
def get_employee_bonus(salary):
bonus = 0 # Default value
if salary > 70000:
bonus = salary * 0.15
return bonus # ✅ Always defined
print(get_employee_bonus(55000)) # 0
print(get_employee_bonus(75000)) # 11250.0
# ✅ Solution 2: Add else clause
def classify_employee(experience):
if experience > 5:
level = "Senior"
elif experience > 2:
level = "Mid"
else:
level = "Junior" # Default
return level # ✅ Always defined
# ✅ Solution 3: Use ternary operator
def get_bonus(salary):
bonus = salary * 0.15 if salary > 70000 else 0
return bonus
# ✅ Solution 4: Return early
def get_bonus(salary):
if salary > 70000:
return salary * 0.15
return 0 # Default return
# ✅ Solution 5: Handle "not found" case
def find_employee(emp_id, employees):
found = None # Default None
for emp in employees:
if emp["id"] == emp_id:
found = emp
break
return found # ✅ None if not found
# Real employee example
employees = [
{"id": 101, "name": "Aarav", "salary": 55000},
{"id": 102, "name": "Ishita", "salary": 72000}
]
def get_employee(emp_id):
for emp in employees:
if emp["id"] == emp_id:
return emp
return None # ✅ Explicit None if not found
print(get_employee(101)) # Aarav's data
print(get_employee(999)) # None4. Cause 3 — global Keyword Usage 🔴
📘 Definition: global keyword Python ko explicitly batata hai — "yeh variable global scope ki hai, LOCAL nahi banao". Ye UnboundLocalError ko fix karta hai jab tum truly global variable modify karna chahte ho. But be careful — globals over-use karna bad practice hai.
💻 Global Keyword Examples:
# Global variables
total_employees = 5
total_salary = 330000
company_name = "TechCorp"
# ✅ Read-only access — no global keyword needed
def print_info():
print(f"Company: {company_name}")
print(f"Employees: {total_employees}")
# Reading is fine — no assignment
print_info() # ✅ Works
# ✅ Modify global — MUST use 'global' keyword
def hire_employee(salary):
global total_employees, total_salary
total_employees += 1
total_salary += salary
print(f"✅ Employee hired. Total: {total_employees}")
hire_employee(60000)
print(f"After hire: {total_employees} employees, ₹{total_salary}")
# Output:
# ✅ Employee hired. Total: 6
# After hire: 6 employees, ₹390000
# ❌ Without global keyword
def wrong_hire(salary):
total_employees += 1 # ❌ UnboundLocalError
total_salary += salary
# ✅ Multiple globals in one statement
def reset_company():
global total_employees, total_salary, company_name
total_employees = 0
total_salary = 0
company_name = "New Corp"
print("✅ Company reset")
# ✅ Verify global change
def check_globals():
print(f"Employees: {total_employees}")
print(f"Salary: ₹{total_salary}")
print(f"Company: {company_name}")⚠️ Why global is BAD PRACTICE:
# ❌ BAD: Heavy use of globals
total_employees = 0
total_salary = 0
department_count = 0
def add_employee(salary, dept):
global total_employees, total_salary, department_count
total_employees += 1
total_salary += salary
# ... more global modifications
# Problems:
# 1. Hard to test (state changes)
# 2. Hard to debug (state can change anywhere)
# 3. Not thread-safe
# 4. Coupling between functions
# ✅ GOOD: Use class or return values
class Company:
def __init__(self, name):
self.name = name
self.total_employees = 0
self.total_salary = 0
def hire(self, salary):
self.total_employees += 1
self.total_salary += salary
return self
def get_stats(self):
return {
"employees": self.total_employees,
"total_salary": self.total_salary
}
# Clean, testable, maintainable!
company = Company("TechCorp")
company.hire(55000) # Aarav
company.hire(72000) # Ishita
print(company.get_stats()) # {'employees': 2, 'total_salary': 127000}5. Cause 4 — nonlocal Keyword (Closures) 🔴
📘 Definition: nonlocal keyword nested functions (closures) mein use hota hai — enclosing function ki variable modify karne ke liye. global module-level ke liye, nonlocal nested function ke enclosing scope ke liye. Advanced concept but important for closures.
❌ Without nonlocal (Error):
# ❌ Employee counter with closure — WRONG
def create_counter():
count = 0 # Enclosing scope variable
def increment():
count += 1 # ❌ UnboundLocalError
return count
return increment
counter = create_counter()
print(counter()) # ❌ Error!
# Reason: Python sees 'count += 1' as assignment inside inner function
# Treats 'count' as local to inner function
# But count is enclosing scope variable
# Result: UnboundLocalError✅ With nonlocal (Fixed):
# ✅ Employee counter — using nonlocal
def create_counter():
count = 0
def increment():
nonlocal count # ✅ Modify enclosing variable
count += 1
return count
return increment
counter = create_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
# ✅ Real-world: Employee ID generator
def create_id_generator(start=101):
current_id = start
def next_id():
nonlocal current_id
result = current_id
current_id += 1
return result
return next_id
generate_id = create_id_generator()
aarav_id = generate_id() # 101
ishita_id = generate_id() # 102
kabir_id = generate_id() # 103
print(f"IDs: Aarav={aarav_id}, Ishita={ishita_id}, Kabir={kabir_id}")
# ✅ Salary tracker closure
def create_salary_tracker():
total = 0
count = 0
def add_salary(amount):
nonlocal total, count
total += amount
count += 1
average = total / count
return {
"total": total,
"count": count,
"average": average
}
return add_salary
tracker = create_salary_tracker()
print(tracker(55000)) # Aarav
print(tracker(72000)) # Ishita
print(tracker(65000)) # Kabir
# Output:
# {'total': 55000, 'count': 1, 'average': 55000.0}
# {'total': 127000, 'count': 2, 'average': 63500.0}
# {'total': 192000, 'count': 3, 'average': 64000.0}📋 global vs nonlocal Comparison:
| Feature | global | nonlocal |
|---|---|---|
| Scope | Module level | Enclosing function |
| Use Case | Modify global variables | Modify closure variables |
| Python Version | All versions | Python 3+ only |
| Creates New Variable? | No — refers to global | No — refers to enclosing |
| Common In | Script-level state | Decorators, closures |
6. Best Solutions — Parameters & Returns 🛠️
📘 Best Practice: UnboundLocalError se bachne ka BEST solution — global variables avoid karo. Instead, use function parameters aur return values. Ye code cleaner, testable, aur predictable banata hai. Modern Python community mein "pure functions" preferred hain — jo external state modify nahi karti.
💻 Best Practice Examples:
# ❌ ANTI-PATTERN: Global state
total_salary = 0
def add_to_total(amount):
global total_salary
total_salary += amount # Hard to test, hidden state
# ✅ BEST PRACTICE: Pure function
def add_to_total(current_total, amount):
return current_total + amount # Testable!
total_salary = 0
total_salary = add_to_total(total_salary, 55000) # Aarav
total_salary = add_to_total(total_salary, 72000) # Ishita
print(total_salary) # 127000
# ✅ Employee management — clean approach
def calculate_bonus(salary, performance_rating):
"""Pure function — no side effects"""
if performance_rating >= 4.5:
return salary * 0.20
elif performance_rating >= 3.5:
return salary * 0.10
else:
return 0
def calculate_total_compensation(salary, bonus, benefits=5000):
"""Pure function — testable"""
return salary + bonus + benefits
def process_employee(employee):
"""Compose multiple pure functions"""
salary = employee["salary"]
rating = employee["rating"]
bonus = calculate_bonus(salary, rating)
total = calculate_total_compensation(salary, bonus)
return {
"name": employee["name"],
"salary": salary,
"bonus": bonus,
"total": total
}
# Usage — clean, no globals
employees = [
{"name": "Aarav", "salary": 55000, "rating": 4.5},
{"name": "Ishita", "salary": 72000, "rating": 4.8},
{"name": "Kabir", "salary": 65000, "rating": 3.9}
]
results = [process_employee(emp) for emp in employees]
for result in results:
print(f"{result['name']}: ₹{result['total']}")
# ✅ Alternative: Use class for stateful operations
class SalaryCalculator:
def __init__(self):
self.total = 0
self.employees = []
def add_employee(self, name, salary):
self.total += salary
self.employees.append({"name": name, "salary": salary})
return self
def get_average(self):
if not self.employees:
return 0
return self.total / len(self.employees)
# Chainable, clean
calc = SalaryCalculator()
calc.add_employee("Aarav", 55000) \
.add_employee("Ishita", 72000) \
.add_employee("Kabir", 65000)
print(f"Average: ₹{calc.get_average():.2f}")7. Debugging Tips 🔍
📋 Debugging Checklist:
| Step | Question | Solution |
|---|---|---|
| 1 | Variable assign hoti hai function mein? | Add global keyword |
| 2 | Conditional block mein assign hoti hai? | Add default value or else |
| 3 | Nested function mein modify? | Use nonlocal keyword |
| 4 | Similar named globals exist? | Rename to avoid confusion |
| 5 | Can restructure to pass parameters? | Best practice — do it |
🔍 Debugging Techniques:
# Technique 1: Check locals() and globals()
def debug_scope():
x = 10
print("Local variables:", locals())
# Shows all local variables
# Technique 2: Print before problematic line
total = 100
def problematic():
try:
print(f"About to use total. Locals: {locals()}")
print(total) # May fail
total = total + 1 # Assignment makes it local
except UnboundLocalError as e:
print(f"Error: {e}")
# Technique 3: dis module — see bytecode
import dis
def my_function():
x = 10
print(x)
dis.dis(my_function)
# Shows LOAD_FAST (local) vs LOAD_GLOBAL
# Technique 4: Explicit scope indication
def safe_function():
# Explicitly declare intent
global some_var
# OR
local_var = some_global # Copy to local first
# Technique 5: Type hints for clarity
def calculate(total: int, amount: int) -> int:
"""Clear inputs and outputs"""
return total + amount
# Technique 6: Use IDE features
# - PyCharm/VSCode highlight local vs global
# - Variable inspection during debugging
# - Set breakpoints before error line8. Interview Questions 💬
Q1: UnboundLocalError kya hai aur kab aati hai?
Ans: UnboundLocalError Python ki built-in exception hai jo tab raise hoti hai jab function ke andar kisi variable ko USE karte ho jo abhi TAK ASSIGN nahi hui, lekin same function mein LATER assign hoti hai. Ye NameError ki subclass hai. Root cause: Python function ko parse karte time DEKHTA hai variables kahan assign hoti hain — assignment presence variable ko LOCAL bana deti hai, even if global exist karti hai. Read before assignment = error. Common in: (1) Global variable modification without global keyword. (2) Conditional assignment without default. (3) Nested function modification without nonlocal. Fix: use global/nonlocal keywords, pass parameters, or initialize variables at function start.
Q2: UnboundLocalError vs NameError mein kya farak hai?
Ans: Dono related hain but different: UnboundLocalError — variable KNOWN hai (local scope mein assignment dikha) but abhi tak VALUE nahi hai — "unbound" state. Function mein assignment hoti hai but read pehle. NameError — variable name Python ko PATA hi nahi — kabhi define nahi hui. Example NameError: print(undefined_var). Example UnboundLocalError: def f(): print(x); x = 5. Technical: UnboundLocalError NameError ki subclass hai. Practical difference: NameError = variable exists nahi, UnboundLocalError = variable exists but abhi value nahi. Debugging different — NameError fix by defining variable, UnboundLocalError fix by proper scope management.
Q3: global keyword kya karta hai aur kab use karo?
Ans: global keyword Python ko explicitly batata hai — "yeh variable global scope se hai, LOCAL nahi banao". Use cases: (1) Function ke andar global variable MODIFY karna. (2) UnboundLocalError fix karna. (3) State manage karna scripts mein. Syntax: def f(): global x; x = 10. Rules: (1) Function start mein declare karo. (2) Multiple globals ek line mein: global x, y, z. (3) Read-only access ke liye global keyword ki zaroorat nahi. Best practices: MINIMIZE global usage — hard to test, debug, thread-safe nahi. Prefer parameters + return values ya classes. Real-world: config settings, counters, feature flags — but even then class-based better hai.
Q4: nonlocal keyword kya hai aur kab use karo?
Ans: nonlocal keyword (Python 3+) nested functions mein ENCLOSING function ki variable modify karne ke liye use hota hai — global nahi, module-level nahi. Use case: closures aur decorators mein. Difference from global: global module-level scope, nonlocal enclosing function scope. Example: def outer():
count = 0
def inner():
nonlocal count
count += 1
Real-world: counter functions, memoization, function factories, decorator implementations. Without nonlocal, inner function ka count += 1 UnboundLocalError deta. Rules: (1) Only Python 3+. (2) Variable must exist in enclosing scope. (3) Cannot bind new variable — only modify existing. Advanced concept but must-know for closures.
Q5: counter += 1 kyu UnboundLocalError deta hai?
Ans: counter += 1 is EQUIVALENT to counter = counter + 1 — is a COMPOUND assignment. Python isse dekh ke: (1) LEFT side assignment hai → counter LOCAL variable declare. (2) RIGHT side counter READ karna hai. (3) But counter abhi tak local mein assign nahi hui — UnboundLocalError! Common trap: developers samajhte hain += "increment" hai, but Python ke liye assignment hai. Same with -=, *=, /=. Fix options: (1) global counter declare at function start. (2) Pass counter as parameter, return updated value. (3) Use class attribute — self.counter += 1. (4) Use nonlocal in closures. Interview mein ye classic question hai — assignment expressions ka understanding test karta hai.
Q6: Python variable scope rules kya hain — LEGB rule?
Ans: LEGB rule — Python variable lookup order: (1) L (Local) — current function scope. (2) E (Enclosing) — outer/enclosing function scope (nested functions). (3) G (Global) — module-level scope. (4) B (Built-in) — Python built-in names (print, len, etc.). Python variables ko is order mein search karta hai. UnboundLocalError tab aati hai jab Local scope mein assignment dikhi but read before assign. Global vs nonlocal: global = G scope, nonlocal = E scope. Common gotcha: function mein assignment karo, variable automatically L scope mein aa jaati hai — even if same name global exists. To modify E or G scope: explicit global or nonlocal declaration. Understanding LEGB is fundamental for Python developers — interview mein always asked.
Q7: global variables use karna bad practice kyu hai?
Ans: Global variables minimize karne chahiye kyunki: (1) Hard to test — functions ka behavior global state pe depend karta hai, unit tests mein setup complex. (2) Hidden dependencies — function signature clear nahi karti kya dependencies hain. (3) Thread safety issues — multi-threaded code mein race conditions. (4) Tight coupling — functions ek dusre ke saath tight coupling develop karti hain global state ke through. (5) Debugging nightmare — state anywhere change ho sakti hai — trace karna mushkil. (6) Refactoring hard — global variable rename ya remove karna risky. Better alternatives: (a) Pure functions — parameters lein, return values den. (b) Classes — state as attributes. (c) Dependency injection — dependencies explicitly pass karo. (d) Config objects — settings ek dedicated config class mein. Modern Python best practice: minimize globals, maximize pure functions.
Q8: Real-world project mein UnboundLocalError kaise prevent karte hain?
Ans: Multi-layered prevention strategy: (1) Code review guidelines — team standards for global usage, PR checks. (2) Linting tools — pylint, flake8, mypy detect scope issues. (3) Type hints — explicit function signatures make scope clear. (4) Pure functions preference — team culture pure functions likhna. (5) Class-based state — instead of module-level globals. (6) Unit tests — edge cases test karte hain, scope bugs catch. (7) IDE features — PyCharm/VSCode local vs global highlight. (8) Explicit initialization — variables function start mein declare with defaults. (9) Return early pattern — conditional assignments avoid. (10) Refactoring practice — legacy code mein globals gradually eliminate. Production: static analysis in CI/CD pipeline, code coverage for edge cases. Modern Python teams: functional programming principles, immutability preferred where possible.
9. Quick Cheat Sheet 📋
# ══════════════════════════════════════
# COMMON CAUSES
# ══════════════════════════════════════
# 1. Read before assignment
count = 0
def f():
print(count) # ❌ UnboundLocalError
count = 1 # Assignment makes it local
# 2. Compound assignment
counter = 0
def inc():
counter += 1 # ❌ Same as counter = counter + 1
# 3. Conditional assignment
def get_bonus(salary):
if salary > 70000:
bonus = 1000
return bonus # ❌ Error if salary <= 70000
# ══════════════════════════════════════
# SOLUTIONS
# ══════════════════════════════════════
# Solution 1: global keyword
count = 0
def increment():
global count
count += 1
# Solution 2: nonlocal (closures)
def outer():
x = 0
def inner():
nonlocal x
x += 1
return inner
# Solution 3: Pass as parameter (BEST!)
def increment(count):
return count + 1
count = increment(count)
# Solution 4: Default value
def get_bonus(salary):
bonus = 0 # Default
if salary > 70000:
bonus = 1000
return bonus # ✅ Always defined
# Solution 5: Return early
def get_bonus(salary):
if salary > 70000:
return 1000
return 0 # Default
# ══════════════════════════════════════
# LEGB SCOPE RULE
# ══════════════════════════════════════
# L - Local (current function)
# E - Enclosing (outer function)
# G - Global (module level)
# B - Built-in (Python built-ins)
# ══════════════════════════════════════
# global vs nonlocal
# ══════════════════════════════════════
# global — module-level variable
x = 10
def f():
global x
x = 20
# nonlocal — enclosing function variable
def outer():
y = 10
def inner():
nonlocal y
y = 20
# ══════════════════════════════════════
# BEST PRACTICES
# ══════════════════════════════════════
# ❌ AVOID: Heavy global usage
total = 0
def add(x):
global total
total += x
# ✅ PREFER: Pure functions
def add(total, x):
return total + x
# ✅ BETTER: Classes for state
class Calculator:
def __init__(self):
self.total = 0
def add(self, x):
self.total += x
# ══════════════════════════════════════
# GOLDEN RULES
# ══════════════════════════════════════
# 1. Assignment in function = local variable
# 2. Read before assign = UnboundLocalError
# 3. Use 'global' to modify globals
# 4. Use 'nonlocal' for closures
# 5. Prefer parameters over globals
# 6. Initialize variables at function start
# 7. Add default values for conditional assigns
# 8. Return early instead of unset variables
# 9. Understand LEGB scope rule
# 10. Classes better than heavy global state• 🔗 UnboundLocalError = variable used before assignment in local scope
• 🔍 Root cause: Python sees assignment → treats as local variable
• ✅ Fix:
global keyword for module-level variables• 🎯
nonlocal for enclosing function variables (closures)• 💡 Best solution: pass parameters, return values (pure functions)
• 🛡️ Initialize variables at function start with defaults
• 📊 Understand LEGB scope rule for Python
• 💼 Production: minimize globals, use classes for state, pure functions preferred
Next: Data Insights Errors Fix Guide
Agle blog mein hum cover karenge: Python RecursionError — Complete Fix Guide. Maximum recursion depth exceeded error, kaise recursive functions manage karo, iterative solutions, aur real-world scenarios employee data ke saath. Errors series continues — Pandas errors sab upcoming. Data Insights par!
Happy Debugging & Keep Coding! 🚀
💬 Comments (0)
Loading comments...