Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Functions Module 4 - Functions Python Python Basics Python Programming: From Zero to Real-World Applications

Scope in Python - Local, Global, and nonlocal Variables

Reviewed & accurate
AI Summary

What You Will Learn

Intermediate

  • The LEGB scope rule
  • global and nonlocal keywords
  • Variable lifetime

The LEGB Rule

Python searches for variables in this order:

  1. L - Local (inside the current function)
  2. E - Enclosing (in outer function)
  3. G - Global (module level)
  4. B - Built-in (print, len, range...)
Terminalpython
x = "global"

def outer():
    y = "enclosing"
    
    def inner():
        z = "local"
        print(x)   # global
        print(y)   # enclosing
        print(z)   # local
    
    inner()

outer()

Modifying Globals

Terminalpython
count = 0

def increment():
    global count    # Tell Python to use the global variable
    count += 1

increment()
increment()
print(count)   # 2

# Without global, this would create a LOCAL variable
# and raise UnboundLocalError
Avoid global
Using global is usually a code smell. Pass values as parameters instead. It makes code harder to test and debug.

Practical Exercise

Create a global variable: x = 10
Define a function that reads x (works!)
Try to modify x inside a function (fails!)
Use global x to modify it
Define a nested function and use nonlocal

Key Takeaways

  • LEGB: Local, Enclosing, Global, Built-in.
  • Functions can READ globals but not MODIFY them without global keyword.
  • global: modify a module-level variable.
  • nonlocal: modify an enclosing function variable.
  • Avoid global - use parameters and return values.
Previously: Lesson 26 covered *args/**kwargs.
Today: You learned: Understand where variables are visible.
Next: Lesson 28 covers lambda.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments