Concepts / Scope and Variable Lifetime in Functions

Scope and Variable Lifetime in Functions

When a variable is declared inside a function definition, its name is local to that function.

  • 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…

The Same Name, Different Variable

A variable name can appear inside a function and elsewhere in a program without referring to one shared variable. When a variable is declared inside a function definition, its name is local to that function. An outside variable with the same name is not related to it. Scope describes the part of the program in which a variable name belongs.

valueoutside the functionvalueinside the function
How can a variable inside a function be different from an outside variable with the same name?

Reading a Function's Local Scope

A function definition creates a block in which names declared inside that function are local. The scope of such a name is the function's block. This means that the name belongs to that function's local context rather than being related to an outside name with the same spelling.

ProgramFunction blocklocal namedeclared inside functioncontainsdeclares
Which parts of the program can access a variable declared inside a function?
Worked example

Two Independent Names

Consider an outside variable named total and a variable named total declared inside a function. Are they the same variable?

  1. 1
    Locate the first name

    The first total is outside the function, so it belongs to the outer part of the program.

  2. 2
    Locate the second name

    The second total is declared inside the function, so its name is local to that function.

  3. 3
    Compare their relationship

    The source states that variables declared inside a function are not related to outside variables with the same names.

Result

The two total names refer to separate scope contexts rather than one shared variable.

Scope Starts at Definition

Definition

A variable has the scope of the block in which its name is declared, beginning at the point where that name is defined.

The phrase beginning at the point of definition matters. It does not describe the entire block without qualification. Instead, the name's scope begins when the name is defined and continues within the relevant block according to the language rules governing that block.

Before definitionoutside the name's statedscopeDefinition pointscope beginsAfter definitionwithin the blockreachescontinues
From which point in a block can a newly declared variable be used?

Tracing Local Lifetime Carefully

Scope and lifetime are related questions, but they are not identical. Scope asks where a name belongs in the program. The provided source establishes that a name declared inside a function has the function's block as its scope and that the scope begins at the point of definition. It does not specify a separate rule describing exactly when the variable is created or removed during function execution.

Function definitionName definitionscope begins hereFunction blockstated scopeAdditional lifetimerulenot specified in the sourcecontainsstarts scope inneeds more rules for
How should the scope of a function-local variable be traced without assuming unspecified lifetime rules?

Changing an Outside Name

The source identifies a special rule for assigning a value to a name defined at the top level of the program. If the assignment occurs inside a function, Python requires the global statement to tell Python that the name is not local. Without that statement, the source says it is impossible to assign to a variable defined outside the function.

Worked example

Recognizing the Global Case

A programmer wants an assignment inside a function to affect a name defined at the top level. Which issue must be addressed?

  1. 1
    Identify the name's original location

    The name was defined at the top level, outside the function.

  2. 2
    Identify the assignment location

    The assignment is being made inside a function, where names are local unless Python is told otherwise.

  3. 3
    Apply the stated rule

    The source says to use the global statement when assigning to a top-level name from inside a function.

Result

The global statement is required for the assignment to target the top-level name rather than being treated as a local assignment.

Mistakes Beginners Make

  • Common mistake

    Assuming that identical spellings identify one shared variable.

    What it looks like

    An outside name and a name declared inside a function both use the spelling count.

    Why it fails

    The source states that a variable declared inside a function is not related to an outside variable with the same name.

    Do this instead

    Classify each name by the block in which it is declared.

  • Common mistake

    Treating a function's local name as belonging to the entire program.

    What it looks like

    A name declared inside a function is discussed as though every part of the program can use it.

    Why it fails

    The name has the scope of the function's block.

    Do this instead

    Start by locating the function block, then locate the name's definition inside that block.

  • Common mistake

    Ignoring the point of definition.

    What it looks like

    A learner assumes that a name has its scope throughout the whole block, even before the name is defined.

    Why it fails

    The source says that scope starts at the point of definition.

    Do this instead

    Mark the definition point before deciding where the name's scope begins.

  • Common mistake

    Expecting an assignment inside a function to change a top-level name automatically.

    What it looks like

    A function assigns to a name defined outside the function without using the stated declaration.

    Why it fails

    The source says that the global statement is required to assign to a top-level name from inside a function.

    Do this instead

    Use the global statement when the intended target is a top-level name.

Scope Tracing Practice

EASY

A program contains an outside name called message and a second name called message declared inside a function. Explain whether the two names are related, identify the scope of the inner name, and state where that scope begins.

Hints
  • Compare the blocks in which the two names are declared.
  • Use the source definition of a function-local name.
  • Remember that scope begins at the point of definition.
MEDIUM

A function attempts to assign a value to a name defined at the top level. What declaration does the source say is needed, and what does that declaration communicate?

Hints
  • Look for the source rule about assigning to a top-level name.
  • The required declaration tells Python that the name is not local.

Key Takeaways

  1. 1
    A name declared inside a function is local to that function's block.
  2. 2
    An inside name and an outside name with the same spelling are not related according to the source.
  3. 3
    A variable's scope begins at the point where its name is defined.
  4. 4
    Assigning to a top-level name from inside a function requires the global statement described by the source.
  5. 5
    The source establishes scope rules but does not provide a complete rule for the variable's creation and removal over time.

At a glance

  • Function-local names belong to the function block in which they are declared.
  • The same spelling in an outside scope does not make two variables related.
  • Scope begins at the point of definition.
  • The global statement is required when assigning inside a function to a top-level name.
  • Scope and lifetime should not be treated as identical concepts without additional language rules.

Related concepts

More concepts starting with S