H2K Infosys Forum

AI Assistant
How does Python det...
 
Notifications
Clear all

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

 
Member Moderator
Translate
English
Spanish
French
German
Italian
Portuguese
Russian
Chinese
Japanese
Korean
Arabic
Hindi
Dutch
Polish
Turkish
Vietnamese
Thai
Swedish
Danish
Finnish
Norwegian
Czech
Hungarian
Romanian
Greek
Hebrew
Indonesian
Malay
Ukrainian
Bulgarian
Croatian
Slovak
Slovenian
Serbian
Lithuanian
Latvian
Estonian

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: