Return values and scope
Overview
This lesson answers two questions every function raises: how do I get results out, and which variables can a function see? The answers — return values and scope — are what make functions safe, independent building blocks.
Returning several values
A function can return several values separated by commas. Python packs them into a tuple, and the caller unpacks it:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 8, 15, 16])
print(low, high) # 4 16For more than three or four values, return a dictionary or a dataclass instead, so the caller doesn’t have to remember the order.
Early returns
return ends the function immediately. That lets you deal with special cases at the top and keep the main logic un-indented:
def shipping_cost(total, country):
if total < 0:
raise ValueError("total can't be negative") # see "Raising exceptions"
if total >= 100:
return 0
if country == "IN":
return 5
return 15These are often called guard clauses. Compare that with the same logic as nested if/else blocks — the early-return version reads top to bottom like a checklist.
Also handy: returning from inside a loop as soon as you find something, which stops both the loop and the function:
def find_user(users, name):
for user in users:
if user["name"] == name:
return user
return None # not foundReturning None
A function that sometimes has no answer can return None. The caller should check for it:
user = find_user(users, "Zoe")
if user is None:
print("No such user")Be consistent: if one path returns a value, every path should return something — even if it’s an explicit return None.
Local variables
Variables created inside a function — including its parameters — are local. They exist only while that call runs, and they’re separate from any variables with the same name outside:
def calculate():
total = 100 # local to calculate()
return total
total = 5
calculate()
print(total) # 5 — the outside total is untouchedAnd local variables can’t be seen from outside:
def calculate():
result = 42
calculate()
print(result) # NameError: name 'result' is not definedThis isolation is a feature: you can write a function without worrying about clashing with names elsewhere in your program.
The LEGB rule
When Python sees a name, it searches four places in order and uses the first match:
- Local — names assigned in the current function;
- Enclosing — names in any function that contains this one;
- Global — names assigned at the top level of the file;
- Built-in — Python’s own names, such as
print,lenandrange.
So a function can read a global variable:
TAX_RATE = 0.2
def with_tax(price):
return price * (1 + TAX_RATE) # reads the global — fineReading global constants like this is normal.
Changing globals: the global keyword
Assigning to a name inside a function makes it local — for the whole function. That leads to a confusing error:
count = 0
def increment():
count += 1 # UnboundLocalError
increment()UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueBecause count is assigned in the function, Python treats it as local everywhere in that function, so reading it before assignment fails. You can declare global count to modify the global instead — but that’s almost always the wrong fix. Functions that quietly change globals are hard to test and reason about: their result depends on hidden state.
The better design: pass values in and return results out.
def increment(count):
return count + 1
count = 0
count = increment(count)(The related nonlocal keyword changes a variable in an enclosing function; you’ll rarely need it.)
Pure functions
A function whose result depends only on its arguments, and which changes nothing outside itself, is called pure. Pure functions are the easiest code there is to test, reuse and debug. Not everything can be pure — some functions must print, read files or save data — but aim to keep those at the edges of your program and the calculations in pure functions.
Remember: functions receive data through parameters and give data back with
return. Everything else they create stays local.
Statistics and validation
(1) Write stats(numbers) that returns the minimum, maximum and average as a tuple — but returns None for an empty list. Unpack the result for [4, 8, 15, 16, 23, 42] and print it, then show what happens with []. (2) Write check_password(pw) that uses early returns to give the FIRST problem found — "too short" (under 8 characters), "needs a digit", "needs a capital" — or "ok". Test it on four passwords. (3) The starter’s add_point uses a global variable; rewrite it as add_point(score, points) that returns the new score.
# 1. stats(numbers)
# 2. check_password(pw)
# 3. Rewrite without the global
score = 0
def add_point():
global score
score += 1
add_point()
add_point()
print(score)# 1. stats(numbers)
def stats(numbers):
if not numbers:
return None
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, mean = stats([4, 8, 15, 16, 23, 42])
print(low, high, mean) # 4 42 18.0
print(stats([])) # None
# 2. check_password(pw)
def check_password(pw):
if len(pw) < 8:
return "too short"
if not any(ch.isdigit() for ch in pw):
return "needs a digit"
if not any(ch.isupper() for ch in pw):
return "needs a capital"
return "ok"
for pw in ["abc", "password", "password1", "Password1"]:
print(pw, "→", check_password(pw))
# 3. Rewrite without the global
def add_point(score, points=1):
return score + points
score = 0
score = add_point(score)
score = add_point(score)
print(score) # 2Summary
return a, breturns a tuple that the caller can unpack:x, y = f().returnexits the function immediately — early returns handle special cases first and keep code flat.- Variables assigned inside a function are local: they exist only during that call and don’t affect outside names.
- Python looks up names in Local → Enclosing → Global → Built-in order (LEGB).
- Pass values in as arguments and return results instead of changing global variables.