Scope in Python
Scope defines where a variable is accessible in your code. Python follows the LEGB rule when looking up variable names: Local → Enclosing → Global → Built-in.
Understanding scope prevents bugs and helps write cleaner, more predictable code. We'll explore each level with examples.
Local Scope
Variables defined inside a function are local – only accessible within that function.
Enclosing Scope (Nested Functions)
In nested functions, the inner function can access variables from the outer function.
Global Scope
Variables defined at the top level (outside functions) are global – accessible anywhere.
Modifying Global Variables – global Keyword
To modify a global variable inside a function, use the global keyword.
nonlocal Keyword – For Enclosing Scope
nonlocal lets inner functions modify variables in the enclosing (outer) function.
The LEGB Rule
Python looks up variables in this order:
- Local (inside current function)
- Enclosing (in nested functions)
- Global (module level)
- Built-in (Python's built-in names like print, len)
Common Pitfalls
- UnboundLocalError – reading a variable before assigning in local scope
- Shadowing built-in names (avoid naming variables print, list, etc.)
Quick Quiz
Wir haben die Materialien überprüft, dennoch können Fehler vorkommen. Der Inhalt dient ausschließlich Bildungszwecken, daher verwende ihn auf eigene Verantwortung und überprüfe ihn bei Bedarf mit anderen Quellen.
✨ Frag Lara — deine KI-Lernpartnerin
Entsperre personalisierte Lernunterstützung. Lara kann Lektionen erklären, Themen zusammenfassen und deine Lernfragen beantworten — verfügbar ab dem Go-Tarif.
Lara hilft dir, schneller zu lernen — exklusiv für ReadyTools Go-, Plus- und Max-Mitglieder.

