Variable Scope (Local, Global, Nonlocal) in Python
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.
Local by default
A variable assigned inside a function exists only while that function runs.
Global variables are visible everywhere
A variable assigned at the top level is readable from inside any function.
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.
global unlocks reassignment
Used inside a function, it tells Python an assignment there should modify the actual global variable.
nonlocal does the same for an enclosing function
Used when a function defined inside another function needs to modify its enclosing function’s variable.
count = 0 def increment(): global count count += 1 increment()increment()print(count)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.