return
return ends the function and hands a value back to whoever called it.
Used in 122 lessons of the course, from 00.01.
return does two things: it stops the function at that point and hands a value to the caller.
That value is the result of the call. You can store it in a variable, pass it to another function, or print it.
def double(n):
return n * 2
result = double(4)
If a function ends without return, it gives back None. A bare return also gives back None.
Watch the difference from print(): print() shows something on screen, but gives nothing to the code that called. return is what lets you chain functions together, which is why you will see it in almost every lesson of the course, starting with 00.01.
Any line after a return on the same path never runs.
Reach for it when: a function computes a result that other code will need.
Examples
Common mistake
def add(a, b):
print(a + b)
total = add(2, 3)
print(total)Why: `print()` only shows the value. The function returns nothing, so `total` is `None`.
How to write it: Write return a + b and print outside the function if you want to see it.
Common mistake
def first_even(nums):
for n in nums:
if n % 2 == 0:
return n
return None
print(first_even([1, 2, 3]))Why: The `return None` sits inside the loop, so the function ends on the first pass, at 1.
How to write it: Move the return None out of the loop, aligned with the for.
