Learn Python
>>> functions.scope

Variable Scope (Local, Global, Nonlocal) in Python

#concept

Scope determines where in a program a variable name is visible and usable. A variable created inside a function is local to that function and disappears once it returns; a variable created at the top level of a script is global and visible everywhere. The global and nonlocal keywords let a function explicitly modify a variable outside its own local scope, which is otherwise not allowed.

#how it works
1

Local by default

A variable assigned inside a function exists only while that function runs.

2

Global variables are visible everywhere

A variable assigned at the top level is readable from inside any function.

3

Reading vs reassigning are different

A function can read a global variable freely, but reassigning it without extra syntax just creates a new local variable of the same name instead.

4

global unlocks reassignment

Used inside a function, it tells Python an assignment there should modify the actual global variable.

5

nonlocal does the same for an enclosing function

Used when a function defined inside another function needs to modify its enclosing function’s variable.

#example
count = 0
 
def increment():
global count
count += 1
 
increment()
increment()
print(count)
Output
2
1count = 0 creates a global variable.
2Inside increment(), global count tells Python that count refers to the outer, global variable rather than creating a new local one.
3count += 1 then modifies that actual global variable, not a local copy.
4Calling increment() twice increases the global count each time, so the final printed value is 2.
#use cases
Understanding why a variable assigned inside a function doesn't seem to 'stick' outside it, unless global or nonlocal is used
Maintaining a running total or counter that several different function calls need to update
Writing closures, where an inner function needs to modify a variable from an enclosing function using nonlocal
Avoiding scope-related bugs by generally preferring return values over modifying global state

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.