Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Programming Fundamentals · Grade 9-12

Scope

The region of a program where a variable is accessible.


Quick Answer

The region of a program where a variable is accessible. A variable created inside a function is local: it exists only while that function runs, and only code inside the function can see it. A variable created outside all functions is global and can be read from anywhere. Scope is what lets two functions each use a variable called count without interfering, and it explains a NameError when code reaches for a variable that is out of sight. To get a value out of a function, return it.

Why This Matters

Scope is why large programs written by many people hold together: a teammate's total inside one function can never overwrite yours in another. Once you understand it, you can predict which variable a name refers to on any line and fix NameError and shadowing bugs quickly. Without it, people lean on global variables, any function might change any value, and a bug could hide anywhere.

Intuitive Explanation

Each function call gets its own temporary workspace. When a call starts, Python creates a fresh local scope; the parameters and every variable assigned inside the function live there. When the call returns, that workspace is thrown away. So if a function f has the body y = 5, the variable y exists only during a call to f, and reading y at the top level afterwards raises NameError: name 'y' is not defined.

Lookup runs from the inside out. When code reads a name, Python checks the local scope first, then any enclosing function, then the global scope, then the built-in names; this order is called the LEGB rule. With a global x = 10, a function that only reads x sees 10. Two functions can each have a local count without a collision, because each lives in its own workspace.

The surprise is assignment, and it is the case that looks like a lost update but is not. If a function runs x = 99, Python treats x as a new local variable for the whole function, which shadows the global: inside, x is 99, but the global x is still 10 afterwards. Nothing was lost; there are two variables sharing one name. A function that runs x = x + 1 fails with UnboundLocalError for the same reason, since that local x has no value yet. Declaring global x makes Python use the outer variable, but passing the value in and returning the result is usually the cleaner fix.

Think of it like this. Each function is a room with one-way glass. From inside, you can look out and read the notices on the hallway board, the globals; from the hallway, nobody can see into the room. Writing a name inside the room pins a new note on the room's own wall rather than changing the hallway board, unless you declare global.

Core idea. Scope prevents name collisions. Two functions can each have a variable called 'count' without interfering with each other.


When to Use

Scope is the question to ask when a name gives a NameError, when a function seems to ignore a change to a global variable, or when two parts of a program use the same variable name. Find where each variable is first assigned: inside a function means local, outside every function means global. If the real problem is getting a result out of a function, the tool is a return value; if a function needs data from outside, pass it in as a parameter instead of reaching for a global.

Tip. Ask: Does the answer depend on whether a name created inside a function can be seen or changed from somewhere else?

How to Recognize It

For each name the code uses, find where it was created and where it is being read or changed.

  1. Is a variable created inside a function and then used outside it?

    Yes means it is out of scope there: the local name disappeared when the function ended, so Python raises NameError. Send the value out with a return instead.

  2. Does a function assign to a name that also exists outside it?

    Yes means that in Python the function gets its own local variable and the outer one is untouched unless global is declared. In JavaScript, assigning without let or const changes the outer variable.

  3. Do two functions use the same variable name, such as count, for different jobs?

    Yes means scope keeps them apart, and each call gets its own count. If they are meant to share one value, pass it as one of the Parameters or keep it outside both.

  4. Is the question only about the value a variable holds after some lines run, with no functions involved?

    Yes means scope decides nothing here; trace the Assignment lines in order instead.

Scope vs Variable vs Parameters vs Return Values

Scope questions always involve variables, parameters and returns, so students name the wrong one. Ask whether you need what a name holds, how a value gets in, how it gets out, or where the name can be seen at all.

Scope

Meaning
Scope is the part of a program in which a variable's name can be used, such as only inside one function.
Key test
The question is where a name is visible, not what it holds.
Example
A total created inside add_up() causes NameError when the main program prints total.

Variable

Meaning
A variable is a named place that holds a value, which the program can read and an assignment can replace.
Key test
Asks what value the name holds at a given moment.
Example
After lives = 3 and then lives = lives - 1, lives holds 2.

Parameters

Meaning
Parameters are local variables listed in a function's definition that are filled with the arguments of each call.
Key test
The value enters the function's scope from the call.
Example
def greet(name), called as greet('Lee'), makes name hold 'Lee', but only inside greet.

Return Values

Meaning
A return value is how a result leaves a function's scope and reaches the code that called it.
Key test
The value leaves the function so the caller can keep it.
Example
Inside make_total, t = 11 is local, but return t lets result = make_total() keep 11.

Formula & Notation

Worked Examples

Example 1 — Two functions, one name

Easy

rate = 2 is set at the top of a program. Function pay(hours) has the body total = hours * rate, then return total. Function bonus(points) has the body total = points + 10, then return total. Trace print(pay(5)), then print(bonus(5)), then print(rate).
Show the steps and the answer
  1. pay(5): hours = 5 is local, and rate is not local, so the lookup moves out to the global rate = 2. total = 5 × 2 = 10, which is returned and printed.

    Reading a name checks the function's own scope first and then the global scope.

  2. When pay returns, its local hours and total are discarded.

    A call's local variables last only until that call ends.

  3. bonus(5): a new local total = 5 + 10 = 15 is created, returned and printed.

    This total belongs to bonus alone, so it cannot clash with the total that pay used.

  4. print(rate) prints 2.

    rate is global and was only read, never assigned, inside the functions, so it is unchanged.

Answer: The program prints 10, then 15, then 2.

Takeaway: Each function call has its own local names, so reusing a name like total is safe; globals can be read from inside, but locals never leak out.

Example 2 — Same name, different variable

Standard

score = 0 is set at the top. A function add_points() has one line in its body, score = 50. The program calls add_points() and then runs print(score). A student expects 50. What is printed, and how should the code be written?
Show the steps and the answer
  1. Inside add_points, score = 50 is an assignment, so Python makes score local to that function.

    In Python, assigning to a name anywhere in a function makes it local for the whole function unless it is declared global.

  2. The local score gets 50; the global score is untouched at 0.

    There are now two variables called score, and inside the function the local one hides the global one.

  3. The call ends, the local score is discarded, and print(score) prints 0.

    At the top level, the name score refers to the global variable.

  4. Rewrite: def add_points(s): return s + 50, called as score = add_points(score), which sets the global score to 50.

    Passing the value in and returning the result makes the change happen where you can see it. Declaring global score inside the function would also work, at the cost of a hidden dependency.

Answer: It prints 0, because the function created a local score that shadowed the global. Use score = add_points(score) with a function that returns s + 50.

Takeaway: Assigning to a name inside a function creates a new local variable; it does not change a global with the same name.

Example 3 — Find the mistake: reading a local from outside

Application

Mo writes a function average(a, b) whose body is result = (a + b) / 2. He calls average(8, 6) and on the next line runs print(result). He says: "I calculated result inside the function, so it should print 7.0." The program stops with NameError. Find the mistake and correct it.
Show the steps and the answer
  1. Find where result was assigned: inside average, so it is local to that function.

    It is created during the call and discarded the moment the call ends.

  2. At print(result) the call has finished and there is no global result, so Python raises NameError.

    Mo treated a local variable as if it outlived its function.

  3. Fix: make the body return (a + b) / 2, and write result = average(8, 6) at the top level.

    return carries the value out of the local scope, and the assignment stores it in a global variable the next line can see.

  4. Trace the fix: average(8, 6) returns (8 + 6) / 2 = 7.0, so print(result) prints 7.0.

    This result is a different variable: a top-level one, assigned from the returned value.

Answer: Return the value and store it where it is needed: result = average(8, 6), then print(result) prints 7.0.

Takeaway: A local variable cannot be read after its function returns; send the value out with return and assign it where you need it.

Where You'll See It

  • Lockers at school

    What's inside your locker (a local variable) is only reachable when you open that locker; a poster in the main hallway (a global) is visible to everyone.

  • Two people both named Alex

    Two functions can each have a variable called count without clashing, the same way two different classrooms can each have a student named Alex without confusion.

  • Whispering in a room

    A variable defined inside a function is like a whisper that only people in that room hear; outside the function it's gone, so trying to read it raises a NameError.

Common Mistakes

  1. The slip: A variable created inside a function can be read anywhere later in the program.

    Why it's tempting: You did create the variable and it held a value, so it feels like it should still exist afterward.

    Instead: A local variable only exists inside its function; once the function returns it's gone, and accessing it outside causes a NameError.

  2. The slip: Assigning to a global's name inside a function changes the global.

    Why it's tempting: The names match, so it looks like you're updating the same variable.

    Instead: In Python, assigning inside a function creates a new local variable that shadows the global. You must declare global x (or pass and return it) to change the global itself.

  3. The slip: Using global variables everywhere is simplest, so it's fine.

    Why it's tempting: Globals are reachable from anywhere, which feels convenient and avoids passing arguments.

    Instead: Globals make it hard to trace where a value changed and hard to test; prefer passing data through parameters and returning results.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. count = 0; def reset(): count = 5; then reset(); print(count). What prints, and why?

    Hint: Assigning to a name inside a function creates it in which scope?

  2. def f(): y = 3; return y * 2. Then x = f(); print(x); print(y). What happens?

    Hint: Where does y exist, and for how long?

  3. x = 10; def show(): print(x); then show(). What prints?

    Hint: show() never assigns x. Where does Python look for it?

  4. x = 1; def outer(): x = 2; def inner(): return x; return inner(). What does print(outer(), x) show?

    Hint: inner looks in its own scope first, then the enclosing function, then global.

  5. print(total) raises 'NameError: total is not defined'. total was created only inside a function calculate(). Is the cause scope, or the order of the lines?

    Hint: Where was total created, and where is it being used?

  6. A student writes count = 0; def inc(): count = count + 1; then calls inc() and says: 'This adds 1 to the global count.' What really happens?

    Hint: Assigning to count anywhere in inc makes count local there.

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

Does a loop create its own scope?

In Python, no: a variable created inside a for loop or an if block is still visible after it, so after for i in range(3): the name i still holds 2. Java, C and JavaScript (with let) give each block in braces its own scope, so the same i would be gone after the loop. In Python it is functions, not loops or ifs, that create new local scopes, which is why the LEGB rule has no level for blocks.

Why does count = count + 1 inside a function crash when count is global?

In Python, if a function assigns to a name anywhere in its body, that name is local for the whole function. So in def add(): count = count + 1, the right side tries to read the local count before anything has been stored in it, and Python raises UnboundLocalError. Reading count without assigning to it works fine. Writing global count as the function's first line makes both the read and the write use the global.

What happens to local variables when a function calls itself?

Each call gets a fresh set of local variables, kept in its own frame on the call stack. In a recursive factorial(n), the call with n = 3 and the call with n = 2 each have their own n, so the values never overwrite each other. When a call returns, its frame and its locals are removed and the caller carries on with its own n. This is where scope and Recursion meet.

Learning Path

Scope

You are here

Next →

Nothing after this yet
You need Function (Programming), defining and calling functions with parameters, and Return Values, sending a result back, first. Scope adds the rules for where each variable lives, how long it lasts and which one a name refers to. With it you can debug NameError and shadowing bugs and design functions that share data only through parameters and returns, which is how larger programs, classes and modules stay manageable.

See Also