Concepts / Understanding Variables

Understanding Variables

Local variables belong only to the function in which they are declared and are independent of global variables with the same name.

  • Programming
Interactive lab

Try it: Scope: Local, Enclosing, Global, Built-in

How Python looks up a name Local → Enclosing → Global → Built-in, why assigning to a name inside a function makes it local (and raises UnboundLocalError if it is read first), and what global, nonlocal and closures change.

How it works

  1. Before a function runs, Python marks every name assigned inside it as local to that function, unless it is declared global or nonlocal.
  2. Reading a name searches the local namespace, then enclosing functions, then the module's globals, then the built-ins; the first hit wins.
  3. A local name read before it has a value raises UnboundLocalError (Python does not fall back to the global).
  4. global x makes assignments go to the module namespace; nonlocal x makes them go to the nearest enclosing function.
  5. A function's local frame disappears when it returns, unless an inner function (a closure) still uses its variables.

Default run (10 steps): Ready: Local shadows global. Every name is looked up Local, then Enclosing, then Global, then Built-in. … Finished. Printed: inside: 99 / outside: 10.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. Built-ins shows only the names the script used.

Educational simulation

Loading the simulation…

A Name in Two Places

Imagine that a program has a variable named x outside a function. The function also has a parameter named x and changes that parameter. The repeated name can be confusing, but the important question is not only which name appears. The important question is which block of code contains that name at the moment it is used.

What do you think happens?

Before tracing the function call, predict what happens when a function has a parameter with the same name as a variable outside the function and modifies its parameter.

  • The outside variable must change.

  • The function uses an independent local variable.

  • The local variable remains available after the function returns.

Reveal answer
Answer:

The function uses an independent local variable, and that local variable cannot be accessed after the function returns.

A parameter is a local variable. It receives a value from the caller, but modifying the parameter does not change the caller's variable. Local variables are created when the function is called and destroyed when the function returns.

xoutside the functionxfunction parameterFunctionlocal scopeavailable insideseparate from
Which variable does each part of the program refer to when a function has a local name matching a name outside the function?

Scope Follows the Defining Block

Scope is the part of a program in which a variable name can be used. The source material describes scope as being determined by the block in which a variable is defined. A function creates a boundary: variables declared inside that function are accessible only within that function. A variable declared outside all functions is global and can be accessed from anywhere in the program.

Definition

A local variable belongs only to the function in which it is declared. It is independent of a global variable with the same name.

Programglobal scopeFunctionlocal scopelocal namedefined inside functionAfter returnlocal name unavailablecontainsdefinesends at return
Which blocks can access a variable, and where does that variable stop being visible?

Tracing a Function Call

Worked example

A Parameter Shadows the Outside Name

Trace a program with an outside variable named score and a function whose parameter is also named score. The function changes its parameter and then returns.

  1. 1
    Before the call

    The program has an outside variable named score. This variable belongs to the outer, global scope.

  2. 2
    At the call

    The argument's value is passed into the function parameter. The parameter is a new local variable belonging to that function call.

  3. 3
    Inside the function

    The name score refers to the local parameter because that is the most local scope available inside the function. Changing this local variable does not change the caller's variable.

  4. 4
    After the return

    The function's local variable is destroyed when the function returns. The local score cannot be accessed after the function ends, while the outside score remains independent.

Result

The matching names do not make the variables the same variable. Inside the function, score refers to the local parameter; outside the function, score refers to the outside variable.

Use namescoreFunction scopelocal name available?Local scoreuse inside functionOutside scoreuse when no nearer nameexistssearch nearest scopeyesno local name
At each point in a function call, how does the program determine which variable a name refers to?

The phrase most local scope available is a useful tracing rule. When a name is used, first inspect the current function or block. If that block defines the name, use that local variable. A name outside the function is relevant only when a nearer local definition is not available.

Parameters and Local Lifetime

A function parameter is a local variable. When the function is called, the parameter receives its value from the argument supplied by the caller. The parameter exists within the function call, so the function can use and modify it while the function is running. Modifying the parameter does not change the caller's variable. When the function returns, its local variables are destroyed and cannot be accessed after the function ends.

No local parameterbefore the callLocal parameterreceives caller valueLocal variabledestroyedafter returnModified parameterinside functionfunction calledfunction changes itfunction returns
What happens to a function's local parameter when the function receives an argument, changes its internal value, and returns?

Debugging Scope Confusion

When a scope-related problem appears, trace the program at the point where the name is used. Identify the active function or block, list the variables defined there, and then check whether the name also exists outside that block. The name refers to the most local scope available. Finally, check whether the function has already returned, because its local variables are no longer available after that point.

Outer blockoutside variableActive functionlocal scopeName usewhich score?Function returnlocal scope endscontainscheck local name firstends at
When a scope-related error occurs, how can you trace the active blocks and identify the variable the program is trying to use?
  • Common mistake

    Assuming that two variables with the same name are automatically the same variable.

    What it looks like

    An outside variable and a function parameter can both be named x.

    Why it fails

    A function creates a boundary, and the parameter belongs to the function's local scope.

    Do this instead

    Track the block in which each name is defined.

  • Common mistake

    Assuming that changing a parameter changes the caller's variable.

    What it looks like

    A function receives an argument, modifies its parameter, and then returns.

    Why it fails

    The parameter is a local variable that receives a value from the caller.

    Do this instead

    Trace the parameter and the caller's variable as separate variables.

  • Common mistake

    Trying to use a local variable after its function has returned.

    Why it fails

    Local variables are destroyed when the function returns.

    Do this instead

    Check whether the name is being used within the function that defines it.

  • Common mistake

    Looking only at the spelling of a name instead of its scope.

    Why it fails

    A name refers to the most local scope available at the point where it is used.

    Do this instead

    Identify the active block first, then determine which definition is nearest.

Best practice

For scope debugging, make a short trace with four questions: Where is the name defined? Which function or block is active? Is there a more local definition with the same name? Has the function that created the local variable already returned?

Scope Tracing Practice

MEDIUM

A program has an outside variable named count. A function also has a parameter named count. During the function call, the parameter is modified. Trace the two names and explain what remains available after the function returns.

Hints
  • Mark the outside count and the parameter count as separate variables.
  • The parameter is local to the function.
  • Check the lifetime of the parameter at the return boundary.
  1. 1
    Locate where each variable with the name count is defined.
  2. 2
    Identify which function or block is active when count is used.
  3. 3
    Choose the most local definition available in that block.
  4. 4
    Separate changes to the local parameter from the outside variable.
  5. 5
    After the function returns, remove the local parameter from your trace.

What to Remember

  1. 1
    A function creates a boundary for local variables.
  2. 2
    A local variable belongs only to the function in which it is declared.
  3. 3
    A name refers to the most local scope available where the name is used.
  4. 4
    A function parameter is a local variable that receives its value from the caller.
  5. 5
    Local variables are destroyed when the function returns, and modifying a parameter does not change the caller's variable.

At a glance

  • Scope is determined by the block where a variable is defined.
  • Variables with the same name can be independent when they belong to different scopes.
  • Inside a function, the most local available definition is used.
  • Function parameters are local variables, so changing a parameter does not change the caller's variable.
  • A function's local variables exist during the function call and are destroyed when the function returns.

Related concepts

More concepts starting with U