Explain the Python Scope with example.
Ask by ICSM Computer
Updated 07 Oct 2025
The 4 Types of Scope (LEGB Rule)
Python follows the LEGB rule, which stands for:
len,print,sum) — always available.localx = 5inside a functionenclosingglobalglobal xbuilt-inprint(),len()Example: Understanding Scope
Output:
Modifying Variables Across Scopes
If you want to modify a variable from an outer scope, use:
global→ to modify a global variable.nonlocal→ to modify an enclosing variable in a nested function.Example:
Output: