Once you’ve learned how to define and use functions in Python, the next important step is to understand where your variables live and how long they stay alive — this is what we call scope.
Let’s break this down with simple examples and clear explanations!
🔍 What is Variable Scope?
In Python, scope refers to the region of a program where a variable is recognized. A variable’s scope determines:
- Where it can be accessed
- Where it can be modified
- Where it no longer exists
There are mainly two types:
- Local Scope
- Global Scope
Let’s explore each.
🏠 Local Scope
A local variable is declared inside a function and is accessible only within that function.
👉 message
is local to the greet()
function. You can’t access it outside.
🌍 Global Scope
A global variable is declared outside all functions and can be accessed anywhere in the program.
👉 Since message
was defined outside, it's globally accessible.
🔁 Modifying Global Variables Inside a Function
You can read global variables inside functions, but to modify them, you must use the global
keyword.
⚠️ Without global
keyword:
Why the error? Python thinks you’re creating a new local count
, but it sees you trying to use it before it's defined.
✅ With global
keyword:
Now you’ve told Python clearly — “I’m referring to the global count
!”
🎯 Good Practice Tip
Using global
too much can make your program hard to debug. It’s better to use function arguments and return values whenever possible.
🚀 Bonus: Variable Scope in Action
Same name, different values — because they exist in different scopes.
📌 Optional: Nested Functions & nonlocal
keyword
(For advanced learners)
When you define a function inside another function, you can use the nonlocal
keyword to modify a variable in the enclosing function.
We’ll explore this in depth in future lessons!
✅ Summary
- Local variable: Declared inside a function, accessible only there.
- Global variable: Declared outside functions, accessible everywhere.
- Use the
global
keyword only when necessary.
Understanding scope helps you write cleaner, bug-free programs and is a must-know for every Python programmer!