Intermediate · Functions · topic 21 of 50 · 25 min
Scope: where variables live
Explanation
Where does a name live?
The scope of a variable is the part of the program where that name can be used. A variable created inside a function is local: it lives only inside that function, while the function runs. A variable created outside all functions, at the top level of the file, is global: it can be read everywhere.
city = "Mumbai"
def show():
city = "Pune"
print("inside:", city)
show()
print("outside:", city)def make_bill():
total = 500
make_bill()
print(total)LEGB: how Python finds a name
When you use a name, Python searches up to four places in this order and uses the first one it finds. The order is called LEGB:
- Local: inside the current function.
- Enclosing: inside an outer function, when this function is written inside another one.
- Global: at the top level of the file.
- Built-in: the names Python itself gives you, like print, len and sum.
UnboundLocalError
If a function ASSIGNS to a name anywhere in its body, Python treats that name as local in the whole function. So reading it before the assignment fails, even when a global with the same name exists.
count = 0
def add_visit():
count = count + 1
return count
add_visit()The global keyword, and why to avoid it
count = 0
def add_visit():
global count
count = count + 1
return count
add_visit()
add_visit()
print(count)nonlocal: changing a variable of the outer function
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step
counter = make_counter()
print(counter(), counter(), counter())lambda: a tiny one-line function
double = lambda n: n * 2
print(double(21))
items = [("rice", 50), ("oil", 160), ("salt", 20)]
print(sorted(items, key=lambda item: item[1]))Watch the lesson
Scope: where variables live · 1/7
In this lesson you will learn where variables live, which is called scope.
Prefer a video by a teacher? Find free videos on “python variable scope global nonlocal lambda tutorial” on YouTube ↗
In real life: GST on a shopping cart
A billing program keeps the GST rate in one global constant, written in capital letters so everyone knows it should not change. Functions read it but never change it. Everything else, like the tax on one item, stays local inside the function, so it cannot clash with other parts of the program.
GST_RATE = 18
def price_with_gst(price):
tax = price * GST_RATE / 100
return price + tax
cart = [100, 250, 40]
total = 0
for p in cart:
total += price_with_gst(p)
print("Total with GST: Rs", round(total, 2))Practice (0/3 done)
This add_visit() function crashes with UnboundLocalError because it changes the global variable visits. Add one line so that it updates the global visits and returns the new value.
items is a list of (name, price) tuples. Write a function cheapest_first(items) that returns a new list sorted by price, lowest first. Use sorted() with key=lambda.
make_counter() should return a function. Each call of that function returns the next number: 1, then 2, then 3. Right now step() crashes because it changes count from the outer function. Fix it with one line.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.