H2K Infosys Forum

How does Python det...
 
Notifications
Clear all

How does Python determine whether a variable is local or global?

 
Member Moderator

Python follows the LEGB rule (Local, Enclosing, Global, Built-in).
When you reference a variable, Python checks in this order:

  • Local – variables inside the current function

  • Enclosing – variables in outer functions (nested functions)

  • Global – variables at the top level of the script

  • Built-in – Python’s built-in names

This resolution process is essential for beginners who want to Learn Python Online, as understanding LEGB helps you write cleaner, bug-free code. The first match determines the scope.


Quote
Topic starter Posted : 03/12/2025 6:13 am
Share: