Scope (local/global variables)
20 minutes read
Beginner friendly
Includes practice
Today we’ll uncover why some variables seem to “disappear” the moment a function ends, while others stick around.
That invisible border is called scope. Once you grasp it, many confusing bugs suddenly make sense.
Runtic's Learning Tips
Think of scope visually: global variables are like hallway lamps, visible from different rooms.
When debugging, ask: “Where was this variable defined?”
Practice isolating scope mistakes—guess what will happen before running the code.
Lesson roadmap
- Build an intuition for scope.
- Compare global and local variables.
- Learn the
LEGBname-lookup rule. - Practice with short coding drills (answers
notshown). - Summarize the big ideas so they stick.
Remember: Struggling a bit is normal. Each “aha!” actually rewires your brain — so lean into it!
Warm-up (Prediction First!)
Interactive Code EditorExample Code
pythonThis won’t affect your saved progress.
Without running it, predict the two printed lines:
- Inside → ?
- Outside → ?
(Jot down your guess—retrieval practice boosts memory.)
What Is Scope?
Imagine your program is a house:
- The hallway =
globalscope (everyone can see). - Each room =
localscope created when a function runs (private while you're inside). - Leave the room, and anything you left “on the floor” vanishes.
Quick Summary
Global variables live in the main program body and are visible almost everywhere.
Local variables are created and vanish within the life of a function call.
Understanding scope prevents accidental overrides and confusion.
Global Variables – Living in the Hallway
Interactive Code EditorExample Code
pythonThis won’t affect your saved progress.
Because language is global, any function can read it freely unless reassigned.
Local Variables – Room-Only Items
Interactive Code EditorExample Code
pythonThis won’t affect your saved progress.
The variable message exists only while the function runs. It's not visible from the outside.
Writing to a Global from Inside a Function
Interactive Code EditorExample Code
pythonThis won’t affect your saved progress.
Why the error?
- Seeing
counter = ..., Python assumes it's creating a local variable. - But it then tries to read that new local before it exists: 💥
UnboundLocalError
✅ Fix with global:
Interactive Code EditorExample Code
pythonThis won’t affect your saved progress.
Style tip: Avoid overusing `global`
- it often indicates design can be improved with return values or parameters.
How Python Looks Up Names – LEGB
- Local — current function
- Enclosing — any outer (nested) functions
- Global — module level
- Built-in — Python's core names like
len,print,int
For now, focus on Local vs Global.
But know that Enclosing and Built-in finish the search path.
Practice Blocks – Your Turn
Practice Challenge
You have a global variable wordset to "cat".Inside the function swap(),declare wordas global, then change its value to "dog"and print it inside the function. After calling swap(),print wordagain outside the function to confirm that the global variable was updated.
Use the global keyword to modify the variable word inside the function.
Quick Practice
3 minutesCheck your understanding of how Python handles variable scope inside and outside functions.
A variable created inside a `for` loop that sits inside a function is…
Which keyword lets a function assign to a global variable?
UnboundLocalError usually means:
Wrap-Up Challenge – No global Allowed
Update a counter without using global.
Practice Challenge
Create a function called increment()that returns counter+1.Start with counter=0,then call increment()three times, each time reassigning the result back to counter.Finally, print the counter — it should display 3.
Define increment() to return counter + 1, and update the global counter by reassigning after each call.
- Functions create their own
localscope—variables inside aren’t visible globally. - You can read
globalvariables from inside a function, but writing to them requires theglobalkeyword. - Using too many
globalvariables can make programs fragile; aim for clear data flow with parameters and returns. - Python looks up names using the
LEGBrule: Local, Enclosing, Global, Built-in.
AI Tutor
Solve first — tutor's here to guide.
Runtric might be wrong. Think critically.