A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Variable Scope

College Depth 77 in the knowledge graph ☐ I know this ☆ Set as goal
674topics build on this
327prerequisites beneath it
See this on the map →
Defining and Calling FunctionsFunction Parameters and Argument Passing+2 more→→Call Stack and Function Call ExecutionIntroduction to Classes+1 more
scope local global namespace encapsulation

Core Idea

Scope defines where in a program a variable is visible and accessible. Local variables exist only inside the function where they are created; global variables are accessible throughout the program. Each function call creates its own local scope (a new set of variable bindings), which is discarded when the function returns. Limiting the scope of variables reduces unintended interactions between parts of a program and makes code easier to reason about.

How It's Best Learned

Write functions that use the same variable name as a global and observe which takes precedence. Use a debugger or print statements to show variable values at different points in the call stack.

Common Misconceptions

Explainer

When you started writing functions, you learned that parameters become local variables inside the function body. Variable scope generalizes this idea: it defines the boundaries of where each variable exists and can be accessed. Think of scope as walls around your variables — code inside the walls can see and use the variable, but code outside cannot. This boundary system is what keeps large programs manageable, because it prevents one function from accidentally interfering with another's data.

A local variable is any variable created inside a function (including its parameters). It comes into existence when the function is called and is destroyed when the function returns. If you define `x = 10` inside a function called `calculate()`, that `x` does not exist anywhere outside `calculate()` — trying to use it elsewhere raises a `NameError`. Critically, each *call* to a function gets its own fresh set of local variables. If `calculate()` calls itself recursively (which you'll learn about soon), each invocation has its own independent `x`. This isolation is what makes functions reliable: you can call them from anywhere without worrying about what variable names they use internally.

A global variable is one defined at the top level of your program, outside any function. Global variables are visible everywhere — any function can read them. However, if a function tries to *assign* to a global variable, Python creates a new local variable with the same name instead, which shadows the global. To actually modify the global, you'd need the `global` keyword — but this is almost always a sign of poor design. The problem with relying on globals is that any function can change them at any time, making it hard to predict your program's behavior. When a bug appears, you'd have to check every function in the program to figure out what changed the global.

The practical rule is straightforward: pass data into functions as arguments and get results back through return values. This keeps each function self-contained — its behavior depends only on its inputs, not on hidden external state. When you encounter code where a function reads and modifies global variables, the function becomes unpredictable: its behavior depends on when it's called and what other functions have run before it. Scope discipline — keeping variables as local as possible — is one of the foundational habits that separates clean, debuggable code from tangled, fragile code. This same principle of isolating state will reappear when you learn about classes and encapsulation.

Practice Questions 5 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope

Longest path: 78 steps · 327 total prerequisite topics

Prerequisites (4)

Leads To (3)