► Understanding Scope and Lifetime
Scope and lifetime are fundamental concepts that determine where and how long variables exist in your program. Scope defines where a variable can be accessed, while lifetime determines how long a variable stays in memory.
► Real-World Analogy
Think of scope and lifetime like access to different rooms in a house:
» Your bedroom is your private space (local scope) – only you can access items there
» The living room is shared space (global scope) – everyone in the house can access it
» A note you write exists only while you’re in that room (lifetime)
» Once you leave and close the door, temporary notes disappear (variable destroyed)
► Key Concepts
✓ Local scope: Variables created inside functions
✓ Global scope: Variables created outside all functions
✓ Lifetime: Duration a variable exists in memory
✓ LEGB rule: Local, Enclosing, Global, Built-in lookup order
✓ Variable shadowing: Local variables can hide global ones
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# Local scope example def greet(): message = "Hello" # Local variable print(message) greet() # print(message) # Error: message not accessible outside function # Global scope example count = 0 # Global variable def increment(): global count count += 1 print(f"Count: {count}") increment() increment() print(f"Final count: {count}") # Variable shadowing x = 10 # Global x def show_x(): x = 5 # Local x (shadows global) print(f"Local x: {x}") show_x() print(f"Global x: {x}") |
