Functions and Scope
A High School and Early College Primer for Programmers
You wrote a function. It runs. Then something breaks — a variable isn't found, a value comes back wrong, or a loop inside your function stomps on something outside it. Scope errors and function confusion are where most beginners stall, and a textbook chapter or YouTube video rarely fixes it cleanly.
**TLDR: Functions and Scope** is a focused, 10–20 page primer that cuts straight to what you need to know. It covers how to define and call functions in Python and JavaScript, how parameters and return values actually work (and why printing isn't returning), and how the LEGB rule determines which variable wins when two share a name. It walks through the call stack frame by frame so you can see exactly when variables are created and destroyed — including what happens during recursion. It closes with the pitfalls instructors see most often: mutable default arguments, accidental globals, and functions that try to do too much.
This guide is written for high school students in an intro programming or AP Computer Science Principles course, college students in CS 101, and anyone tutoring or helping a student get unstuck. If you're looking for a short programming reference for students that respects your time and skips the filler, this is it.
Read it once before your next lab or exam and walk in knowing exactly where your variables live.
- Define a function, call it with arguments, and return values correctly
- Distinguish parameters from arguments and positional from keyword arguments
- Trace the lifetime of a variable through local, enclosing, global, and built-in scopes
- Predict what a piece of code prints by reasoning about scope and the call stack
- Recognize and avoid common bugs caused by shadowing, mutable defaults, and unintended globals
- 1. What Is a Function?Introduces functions as reusable, named blocks of code with inputs and outputs, and shows how to define and call them.
- 2. Parameters, Arguments, and Return ValuesCovers positional and keyword arguments, default values, multiple returns, and the difference between returning and printing.
- 3. Scope: Where Variables LiveExplains local, enclosing, global, and built-in scopes and how the interpreter resolves names using the LEGB rule.
- 4. The Call Stack and Variable LifetimeWalks through how each function call creates a new frame, how variables are born and destroyed, and how recursion stacks frames.
- 5. Common Pitfalls and Best PracticesWarns about mutable default arguments, accidental globals, shadowing built-ins, and over-long functions, with fixes for each.
- 6. Why It Matters: Functions as Building BlocksConnects functions and scope to larger ideas: modularity, testing, closures, and the patterns students will see in any language they learn next.