Skip to content
BENIBIX Learn

Scope

Development🧩 Programming ConceptsFunctions

Also known as Variable Scope, Local Variable, Global Variable

Where in a program a name can be seen. Names in a function stay local.

Think of it like

Think of it like rooms in a house. A note left in the kitchen cannot be read from the bedroom.

Example

Lucy makes total inside a function, then tries to print it outside. Python says total is not defined.

Why it matters

Scope keeps big programs safe to change. Two functions can each use a name like count without clashing.

Definition

Scope is the part of a program where a name can be seen and used. A variable made inside a function is local: it only exists in that function. A variable made at the top of the file is global: the whole file can see it. When the function ends, its local names are gone. Keeping names local stops one part of the code from changing another by mistake.

Example code

python
def f():
    total = 5

f()
print(total)
# NameError: name 'total' is not defined
Total lived only in the function. Outside, it does not exist.

Common mistake

Using global variables for everything. Any line can change them, so bugs are hard to trace.

Key takeaways

  1. 1
    Local is safe. Names inside a function stay there.
  2. 2
    Global is shared. Every part of the file can touch it.
  3. 3
    Gone at the end. Local names vanish when the function ends.

Learn it properly