Loading section...

Local vs Global Scope

Concepts: pyFuncScope

Scope determines where a variable is visible and accessible. Python has two main scopes: local (inside a function) and global (module level). Understanding scope prevents bugs where variables unexpectedly share or shadow each other. Scope bugs are especially tricky because the code often looks correct but behaves differently than expected. Every variable in Python lives in a specific scope. When you reference a variable name, Python searches scopes in a specific order to find it. Understanding this lookup order is crucial for predicting how your code will behave, especially in larger programs with many functions. Local Scope Variables created inside a function exist only within that function. They are created when the function runs and destroyed when it returns: Global Scope Variables defi