Variable Scope
Understand local, global, and enclosing scope. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Local VariablesStudy Material
Read the full lesson
Where do variables live?
When you create a variable inside a function, it belongs only to that function.
Imagine you and your friend both have a box labeled secret.
If you put a coin in your secret box, it doesn't miraculously appear in your friend's box. They are two separate boxes that just happen to share the same name.
In Python, this concept is called Scope.
Local Scope
Variables created inside a function are in the Local Scope.
pythondef make_coffee(): cup = "Espresso" print(f"Inside the function, I have {cup}") make_coffee() # Output: Inside the function, I have Espresso print(cup) # Output: NameError: name 'cup' is not defined
Once the make_coffee function finishes running, Python immediately throws away the cup variable. It ceases to exist.
If you try to print it from outside the function, Python will complain because it has no idea what cup is anymore.
Global Scope
Variables created outside of any function are in the Global Scope.
These variables can be seen and read by anyone, anywhere in your code.
pythonweather = "Sunny" def check_weather(): print(f"Inside the function, it is {weather}") check_weather() print(f"Outside the function, it is {weather}")
Both prints will say Sunny. Functions are perfectly happy looking "outward" into the global scope to read data.
The Scope Shadow Warning
What happens if you use the same variable name inside and outside?
pythoncolor = "Red" def paint_wall(): color = "Blue" # This creates a NEW local variable! print(f"Painting wall {color}") paint_wall() # Output: Painting wall Blue print(color) # Output: Red
When you write color = "Blue" inside the function, Python doesn't change the global color. Instead, it creates a brand new local variable that "shadows" (hides) the global one.
Once the function is over, the local Blue is thrown away, and the global Red remains untouched.
What this lesson should give you
After this lesson, you should understand how to:
- keep data safe inside local scope
- read global variables from inside a function
- avoid accidentally hiding global variables by reusing their names
- understand why variables disappear when a function finishes running
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Local Variables
Complete the "Local Variables" exercise.
Read Global
Complete the "Read Global" exercise.
Modify Global
Complete the "Modify Global" exercise.
Variable Shadowing
Complete the "Variable Shadowing" exercise.
Nonlocal Keyword
Complete the "Nonlocal Keyword" exercise.