Lesson 18 of 30

In progress

Course progress

Python

Scope: where names live

Understand local and global names, read the LEGB rule without memorising it, and stop reaching for global variables.

A function that changes a variable it never received is doing two jobs with no visible connection. Scope is the rule that decides which name a line refers to, and it is the reason some functions cannot see your variables at all.

What you will learn

  • Tell local names from global ones.
  • Predict UnboundLocalError before it happens.
  • Pass state through parameters instead of global.

Local names exist only inside the function

A name assigned inside a function is local by default. It appears when the function is called and disappears when it returns.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

The last line raises NameError: name 'amount' is not defined, because amount was never a global. That is a feature: the function’s scratch variables do not leak into the rest of the program and cannot collide with yours.

Parameters are local too. Rebinding name inside a function does not change the caller’s variable, because the name inside points at a new value.

Global names are readable, not assignable

A function can read a module-level variable without any declaration. Assigning to it creates a local instead, unless you say global.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

shadow prints 99 and leaves the global at 10. The assignment created a local named count. If you truly need to change the global, global count works, but the need is usually a design smell.

There is a subtler version: reading and assigning the same name in one function makes the name local for the whole function, so a read before the assignment fails.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

That raises UnboundLocalError: cannot access local variable 'total' where it is not associated with a value. Python decided total was local because of the assignment, then found it unread before it was set. The fix is to pass the current total in and return the new one, not to add global.

The lookup order, without the acronym

When a line uses a name, Python checks the local scope first, then any enclosing function, then the module, then the built-ins. The acronym LEGB is popular; the useful part is the first step. A local name hides a global of the same name, which is why naming a variable sum breaks your later calls to sum() inside that function.

Closures use the enclosing step. A nested function can read a name from the function that contains it.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

greet remembers prefix after make_greeting has returned. That is a closure, and it is the clean alternative to a global configuration value.

Prefer parameters and return values

State passed explicitly is visible at the call site, easy to test and safe to run twice. State in a global is invisible until it goes wrong.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

The function receives what it needs and returns the new value. Nothing outside it changes behind your back, and calling it with different numbers is trivial.

global inside a function that is called from several places makes the order of calls matter. Two calls give different results, tests interfere with each other, and the bug depends on history rather than input. If you feel the urge to use global, pass the value in and return the new one instead.

This function fails. Fix it without using global, and explain in one sentence what Python thought was happening.

total = 0
def add(amount):
total = total + amount
return total
Show solution
Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Python treated total as local because the function assigned to it, so reading it first raised UnboundLocalError. Passing the running total in as a parameter removes the hidden state, and the returned value is the new total.

Recap

  • Names assigned in a function are local and vanish when it returns.
  • Reading a global works; assigning creates a local unless you declare global.
  • Passing state in and returning it out is clearer than shared mutable state.

Next, you will use code you did not write: the standard library, where Python keeps ready-made modules for maths, dates and randomness.

Is it ever fine to use a global?
For constants that never change, yes: a module-level `MAX_ATTEMPTS = 5` is readable and harmless. For mutable state that functions update, no. The distinction is between a fixed configuration value and a variable pretending to be one.
Why does my loop variable survive after the loop?
Loops do not create a new scope in Python, so the variable belongs to the function or module. That is why a leftover `item` can still be read afterwards. Do not rely on it; assign a clear result instead.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.