Python Variables Scope
May 25, 2023 2023-07-01 15:49Python Variables Scope
Python Variables Scope
Table of Contents
Python has three scopes of variables:
• Local scope
• Global scope
• Enclosing scope
LEGB rule
1. Local scope:
When a variable is declared within a function (see functions in Python), its scope is local. The variable is used within the function and exists only when the function is executed.
2. Global scope:
A global variable is declared outside all functions in the code file and has a scope that covers the entire code file.
If a local variable is declared with the same name as a global variable within a function, the system will use the local variable.
When we want to modify the value of a global variable within a function call, we use the `global` keyword before the variable:
x = 100 # global scope x
def myfunc():
global x
x = 200 print(x)
# x value is 200 inside myfunc myfunc()
print(x)
# x value is 200 outside myfunc
3. Enclosing function
# enclosing function
def f1():
x = 42
# nested function
def f2():
x = 0
print(x) # x value is 0
f2()
print(x) # x value is still 42
f1()
The variable `x` does not change its value after calling the `f2()` function because the system initializes a new memory for the `x` variable inside the `f2()` function. To modify the value of `x` during the logical processing of the `f2()` function, we use the `nonlocal` keyword before the `x` variable:
# enclosing function
def f1():
x = 42
# nested function
def f2():
nonlocal x
x = 0
print(x) # x is now 0
f2()
print(x) # x value is now 0
f1()
Scoping Rule – LEGB Rule
Scoping Rule – LEGB Rule:
When a variable is referenced (used in some logic), Python follows the LEGB rule with the four levels of variable scope in order:
L – Local Scope
E – Enclosing scope (local variables in enclosing functions and lambdas)
G – Global Scope
B – Built-in variables available in Python.
Don’t forget to share this post!
The Tech-Savvy Solopreneur
Recent Posts
- Tailored Strategies for Digital Advertising Success: Solution for Every Step of the User Journey
- DIGITAL AD SPEND (2021–2026) – Insight into Global Trends and Growth Prospects
- Demystifying Ad Marketing Jargon: Easy to understand 17 Key Terms for Success in Digital Marketing
- Navigating Organizational Structures: A Guide for Project Managers (PMs)
- Lean and Six Sigma Methodologies
Recent Comments
- Jack on Test Bo Kho 2
- admin on Test Bo Kho
- Edna Watson on Use SEO to Boost Your Business
- Edna Watson on Use SEO to Boost Your Business
- Scott James on Use SEO to Boost Your Business