Welcome to Day 13 of the 100 Days of Python series!
Today, we’re diving into a super important concept: variable scope.
Have you ever defined a variable inside a function and then tried to access it outside — only to get an error? That’s a scope issue!
Understanding the difference between local and global variables will help you write clean, bug-free code.
📦 What You’ll Learn
- What variable scope means
- The difference between local and global variables
- How scope affects access to variables
- The
global
keyword - Real-world examples and best practices
🔍 What Is Scope?
Scope determines where a variable can be accessed in your code.
In Python, there are two main types:
- Local scope: Variables declared inside a function.
- Global scope: Variables declared outside all functions.
🧪 1. Local Variables
A variable defined inside a function is local to that function.
def greet():
name = "Alice"
print("Hello", name)
greet()
print(name) # ❌ Error: name is not defined
name
only exists inside the greet()
function. Trying to access it outside causes an error.
🌍 2. Global Variables
A variable defined outside all functions is global and can be accessed from anywhere in the script.
message = "Welcome!"
def greet():
print(message)
greet()
print(message) # ✅ This works
⚠️ 3. Modifying Global Variables Inside Functions
You can read global variables inside functions, but to modify them, you need to use the global
keyword.
Without global
:
count = 0
def increment():
count += 1 # ❌ Error: UnboundLocalError
This gives an error because Python treats count
as a new local variable.
With global
:
count = 0
def increment():
global count
count += 1
increment()
print(count) # ✅ 1
Use the global
keyword only when necessary, as it can make debugging harder.
🎯 Real-World Example: User Sessions
# global session
is_logged_in = False
def login():
global is_logged_in
is_logged_in = True
def logout():
global is_logged_in
is_logged_in = False
login()
print("User logged in?", is_logged_in) # True
🧠 Variable Resolution: LEGB Rule
Python uses the LEGB rule to resolve variable names:
- L – Local: Inside the current function
- E – Enclosing: In enclosing function(s) (for nested functions)
- G – Global: Defined at the top level of the script
-
B – Built-in: Provided by Python itself (
print
,len
, etc.)
🧼 Best Practices
- ✅ Prefer local variables to avoid side effects
- ✅ Use function parameters and return values for data transfer
- ⚠️ Avoid using
global
unless absolutely necessary - 🚫 Never use the same name for local and global variables (confusing!)
🧠 Recap
Today you learned:
- What variable scope is and why it matters
- The difference between local and global variables
- How the
global
keyword works - The LEGB rule for resolving variable names
- Why using local scope is often safer
Top comments (0)