Global vs Local Scope Call Stack Explorer
Run the Global vs Local Scope Call Stack Explorer MicroSim Fullscreen
Edit in the p5.js Editor
About This MicroSim
Here is the bug that catches almost everyone: you set eye_size = 20 inside a
function, the function runs, and your robot's eyes stay exactly the same size.
This MicroSim steps through a tiny grow_eyes() function one line at a time and
draws two boxes, one for the global scope and one for the local scope, so you
can see which variable each assignment really changes. Flip between the version
without global and the version with it, and you will be able to tell a local
variable from a global one that happens to share its name.
How to Use
- Leave the Version dropdown on Without global for your first run.
- Click Step to execute one line. The highlighted line shows where you are.
- Watch the Global Scope box, which is always on screen, and the Local Scope
box, which appears only while
grow_eyes()is running. - Read the note under the boxes at each step. It says which variable that line actually changed.
- Click Reset, switch the dropdown to With global, and step through again. Compare the two runs at the moment the assignment executes.
- Notice the final console output:
10in one version and20in the other.
Iframe Embed Code
You can add this MicroSim to any web page by adding this to your HTML:
1 2 3 4 | |
Lesson Plan
Grade Level
9-12 (High School)
Duration
10-15 minutes
Prerequisites
- Know how to define a function with
defand call it by name. - Understand that an assignment such as
eye_size = 10creates a variable. - Know that
print()sends one line of text to the console. - Be able to trace a short program line by line, as in the Loop Tracer MicroSim.
Activities
- Exploration (5 min): Step all the way through the Without global
version. Stop at the step where the Local Scope box shows
eye_size = 20and write down what the Global Scope box says at that same moment. - Guided Practice (5 min): Reset, switch to With global, and step to the same assignment line. Describe in one sentence what the arrow between the two boxes is showing you.
- Assessment (5 min): Predict the console output for each version before stepping to the final line, then explain the difference in your own words.
Assessment
- The student predicts that the version without
globalprints10. - The student explains that assigning inside a function creates a local variable
unless
globalsays otherwise. - The student defines shadowing: a local name hiding a global name.
- The student states when the local scope is created and when it is discarded.
References
- MicroPython Documentation - the official reference for the MicroPython language.
- Python reference: the
globalstatement - the exact rule MicroPython follows for global declarations. - Scope (computer science) (Wikipedia) - background on how programming languages decide which variable a name means.
- Variable shadowing (Wikipedia) - the specific behavior this MicroSim makes visible.