Return Values & Multiple Results
By the end of this lesson you will be able to decide exactly what a function should give back, spot the hidden None that breaks programs, and return several results in a way that stays readable. Good return values are what make a function easy to reuse.
You met return in Functions: it sends a value back and ends the function, and return a, b gives back a tuple. This lesson goes deeper, into the bugs and design choices that come up once your functions grow.
A call becomes its return value
Think of a railway enquiry counter. You ask a question (the call), the clerk works it out (the body), and hands you a printed slip (the return value). What you do with the slip is your choice. You can read it, keep it, or pass it to someone else.
A function call works the same way. When the function returns, the whole call is replaced by the returned value. So you can use a call anywhere a value is allowed: in a calculation, in an if, inside an f-string, or as an argument to another call.
def fare(km, rate_per_km):
return km * rate_per_km
def with_gst(amount):
return round(amount * 1.05, 2)
pune_to_mumbai = fare(150, 1.6)
print(pune_to_mumbai)
print(with_gst(fare(150, 1.6)))
if fare(300, 1.6) > 400:
print("Long trip: book a sleeper berth")
print(f"Total for 2 tickets: ₹{2 * with_gst(fare(150, 1.6)):,.2f}")240.0 252.0 Long trip: book a sleeper berth Total for 2 tickets: ₹504.00
with_gst(fare(150, 1.6)) runs from the inside out. First fare() returns 240.0. Then that value is passed to with_gst(), which returns 252.0. Small functions that return values can be joined like this, like pipes fitted together.
The hidden None
If the body finishes without reaching a return statement, Python returns None for you. This is called the implicit return. It is useful for functions that only do something, such as printing a ticket. But it causes bugs when a function is supposed to give an answer and one path forgets to.
Here is a common example. The function returns a result for passing marks, but nothing for failing marks:
def result(marks):
if marks >= 33:
return "Pass"
for marks in [78, 33, 21]:
print(marks, result(marks))78 Pass 33 Pass 21 None
No error appears, which is what makes this bug dangerous. The None travels on and breaks something later, perhaps a report that tries result(21).upper(). The fix is simple: make sure every path ends in a return.
def result(marks):
if marks >= 33:
return "Pass"
return "Fail"
print(result(21).upper())FAIL
return inside a loop ends the whole function
return does not just stop the loop. It leaves the entire function at once. This is perfect for searching, because you can stop as soon as you find the answer. But a return in the wrong place makes a loop check only the first item.
Step 1: here is the buggy version. It should say whether every student passed.
def all_passed(marks_list):
for marks in marks_list:
if marks < 33:
return False
else:
return True
print(all_passed([45, 20, 88]))True
The answer is wrong. On the first pass, 45 is not below 33, so the else branch returns True and the function ends. The 20 is never checked.
Step 2: move the "everything is fine" answer after the loop. You can only say "all passed" once you have looked at every mark.
def all_passed(marks_list):
for marks in marks_list:
if marks < 33:
return False
return True
print(all_passed([45, 20, 88]))
print(all_passed([45, 60, 88]))False True
Now the loop returns early only when it finds a failure, which is exactly when the answer is known. You will see a one-line way to write this with all() in Essential Built-in Functions.
Returning more than one result
When a function works out several related results, return them together with commas. Python packs them into one tuple, and the caller can unpack the tuple into names, as you practised in Unpacking & Multiple Assignment.
def innings_summary(scores):
total = sum(scores)
average = total / len(scores)
return total, round(average, 1), max(scores)
kabir = [45, 0, 102, 33, 76]
total, average, best = innings_summary(kabir)
print(f"Total {total}, average {average}, best {best}")
summary = innings_summary(kabir)
print(summary, type(summary).__name__)
_, average, _ = innings_summary(kabir)
print("Only the average:", average)Total 256, average 51.2, best 102 (256, 51.2, 102) tuple Only the average: 51.2
The function really returns one object, a tuple. You can unpack it, keep it whole, or ignore parts with _. If the number of names does not match, you get ValueError: too many values to unpack.
When a tuple is not clear enough
Two or three results in a tuple are fine. Beyond that, callers start mixing up the order. Was it (base, gst, total) or (total, base, gst)? A dictionary gives every result a name, so the order no longer matters.
def bill_breakdown(price, gst_rate):
gst = round(price * gst_rate / 100, 2)
return {
"base": price,
"gst_rate": gst_rate,
"gst": gst,
"total": price + gst,
}
bill = bill_breakdown(1299, 18)
print(bill["total"])
for key, value in bill.items():
print(f"{key:>9}: {value}")1532.82
base: 1299
gst_rate: 18
gst: 233.82
total: 1532.82Later in the course you will meet two even better options for named results: Named Tuples, which keep the tuple shape but add names, and data classes in Dataclasses & Enums.
Return an empty collection, not None
Suppose a function searches a train timetable and returns the matching trains. What should it return when nothing matches? Return an empty list. The caller can then loop over the result, check len() or test it with if without any special case.
timetable = [
("Shatabdi", 6), ("Intercity", 9), ("Garib Rath", 21), ("Duronto", 22),
]
def trains_after(hour):
found = []
for name, departs in timetable:
if departs >= hour:
found.append(name)
return found
late = trains_after(21)
print(late)
none_left = trains_after(23)
print(none_left, len(none_left))
for name in none_left:
print("This line never runs")
if not none_left:
print("No more trains today")['Garib Rath', 'Duronto'] [] 0 No more trains today
If the function returned None instead, len(none_left) and the for loop would both raise TypeError. An empty list is still a list, so every list operation keeps working.
Keep None for "there is no single answer", such as a lookup for one train that does not exist. When a missing value is truly an error, a function can raise an exception instead of returning anything; you will learn that in Raising Exceptions.
Common mistakes
- One path without a return. The function quietly returns
None. Check that every branch, including the end of the body, returns a value. returnin anelseinside a loop. The loop stops after the first item. Put the "all good" answer after the loop.- Printing instead of returning. The caller gets
None. Return the value and let the caller print it. - Returning five values in a tuple. Callers mix up the order. Use a dictionary or a named tuple.
- Returning
Nonefor "no results". Return an empty list, set or dict so callers can loop safely.
Interview questions
1. What does a Python function return if it has no return statement?
It returns None. The same happens with a bare return and when the body runs to the end on a path that has no return. This is why a missing branch often shows up as an unexpected None.
2. Can a function return more than one value?
Strictly, no: it always returns one object. return a, b builds a tuple (a, b) and returns that. The caller can unpack it with x, y = f(), which makes it feel like several values.
3. Is it bad to have several return statements in one function?
No. Early returns are normal and often make code clearer, for example returning as soon as a search finds its item. The rule is to keep them easy to follow and to make sure every path returns the same kind of value.
4. Should a search function return None or an empty list when nothing is found?
If it returns many matches, return an empty list, because callers can loop over it and call len() without a special check. If it returns one item, None is reasonable for "not found", and callers should test it with is None.
Key points
- A function call is replaced by its return value, so calls can be used in expressions and nested.
- Without a
returnon some path, the function gives backNoneon that path; make every path return. returninside a loop ends the whole function; put the "checked everything" answer after the loop.return a, b, creturns one tuple; unpack it, or use_for parts you do not need.- For more than three results, return a dictionary (or later, a named tuple or data class).
- Return an empty collection for "no results", and keep
Nonefor "no single answer".
Exercise
A school in Lucknow stores marks as a list of (name, marks) tuples, for example [("Aarav", 81), ("Isha", 29), ("Rohan", 64), ("Meera", 30)]. Write a function class_report(records) that returns three things: the class average rounded to 1 decimal place, the name of the topper, and a list of names of students below 33. If nobody failed, the list must be empty, not None. Call it, unpack the result into three names and print them. Then call it again with a class where everyone passed.
Show solution
def class_report(records):
total = 0
topper, top_marks = "", -1
failed = []
for name, marks in records:
total += marks
if marks > top_marks:
topper, top_marks = name, marks
if marks < 33:
failed.append(name)
return round(total / len(records), 1), topper, failed
average, topper, failed = class_report(
[("Aarav", 81), ("Isha", 29), ("Rohan", 64), ("Meera", 30)]
)
print(average, topper, failed)
average, topper, failed = class_report([("Kabir", 70), ("Priya", 92)])
print(average, topper, failed)51.0 Aarav ['Isha', 'Meera'] 81.0 Priya []
The function collects everything in one loop and returns one tuple of three values. failed starts as an empty list, so a class with no failures still gets a list back and the caller never has to check for None.
Quick Quiz
1. What does print(f(5)) show if def f(x): x * 2 has no return?
The body calculates x * 2 but never returns it, so the call gives back None.
2. A loop contains if bad: return False and else: return True. What is the bug?
Either branch returns on the first pass, so later items are never checked.
3. What type is r after r = f() when f ends with return 1, 2?
Comma-separated return values are packed into one tuple.
4. What is the best return value for "no matching trains"?
An empty list lets the caller loop over it and call len() without a special case.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
