Understanding Scope and Closures in Python – A Beginner-Friendly Guide


If you’ve ever wondered “Why can’t I access that variable here?” or “What does Python mean by global and local?”, you’re not alone.
In this article, we’ll break down one of the most fundamental concepts in Python: Scope, and briefly touch upon Closures, using relatable analogies and practical code examples.
🏠 What is Scope?
Think of scope as a “house” you build in memory. Every time you define a function, you're essentially creating a new room inside your program. Any variable you define inside this room stays inside unless you deliberately bring it out.
There are primarily four scopes in Python, governed by the LEGB rule:
L – Local (inside the current function)
E – Enclosing (scope of any enclosing functions, useful in closures)
G – Global (module-level)
B – Built-in (Python’s reserved words and functions)
x = 10 # Global scope def outer(): y = 20 # Enclosing scope def inner(): z = 30 # Local scope print(x, y, z) # Accessing all three scopes inner()
📦 How Does Scope Work?
Let’s walk through a simple example:
username = "chai aur code"
def fun():
username = "chai"
print("Inside function:", username)
fun()
print("Outside function:", username)
Output:
Inside function: chai
Outside function: chai aur code
Even though the variable name
username
is the same inside and outside the function, they exist in two different scopes. The inner one shadows the outer.
🧪 The Investigative Trick: Going Upwards
If Python can’t find a variable in the current (local) scope, it looks in the enclosing one, then the global, and finally in the built-in namespace. This “upward” search continues until it finds the variable or throws a NameError
.
x = 5
def add(y):
return x + y
print(add(2)) # Output: 7
Here, x
isn’t defined in the function, but Python finds it in the global scope.
🔒 What is a Closure?
A closure is created when:
A nested function references a variable from its enclosing function
The enclosing function has finished executing
def outer(): msg = "Hello" def inner(): print(msg) # uses 'msg' from outer return inner greet = outer() greet() # Output: Hello
Closures allow the inner function to remember the state of the outer function even after the outer function has completed.
🧠 Why Should You Care?
Understanding scope avoids bugs like unintentionally modifying global variables.
Closures are foundational to concepts like decorators, callbacks, and function factories.
They help you write cleaner, more modular Python code.
🧵 Wrapping Up
Think of scope as building "rooms" in memory. Variables live only in their room unless passed explicitly. Python respects this with its LEGB rule. Once you master this concept, closures become intuitive — they’re just nested rooms remembering values from outer rooms!
👨💻 Whether you're building your first script or diving into more advanced topics like decorators and functional programming, mastering scope is non-negotiable.
Have questions or want to share your own “aha!” moments with scope and closures? Let’s connect in the comments! 👇
#Python #PythonProgramming #Closures #LEGB #BeginnersGuide #LearningPython #TechWithManas
Subscribe to my newsletter
Read articles from Manas Shinde directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
