Part 05 / Topic 1 of 9
def and return
A function is a named block of code. You define it once with def and call it (run it) many times.
Think of a tea machine: you put in water and milk (the inputs), press a button (the call), and get tea back (the output).
return sends a value back to the caller (the line that called the function). print only shows text on the screen.
If a function has no return, it gives back None.
Real-world example: calculate the total of a restaurant bill.
def bill_total(price: float, quantity: int) -> float:
return price * quantity
total = bill_total(120, 3) # value comes back, we can store it
print(total) # 360
print(total + 40) # 400 (we can keep using it)
def show_total(price, quantity):
print(price * quantity) # only shows it, gives back nothing
result = show_total(120, 3) # prints 360
print(result) # None
return |
print |
|
|---|---|---|
| What it does | Sends a value back to the caller | Shows text on the screen |
| Can you store the result? | Yes | No (you get None) |
| Ends the function? | Yes | No |
๐ Going deeper:
defcreates a function object and stores it in a name, just likex = 5.print(type(bill_total))shows<class 'function'>. A barereturn(or noreturn) gives backNone.
Returning many values
Write the values with commas. Python packs them into a tuple. Unpack them on the left side.
def min_max(marks):
return min(marks), max(marks)
low, high = min_max([72, 95, 64, 88])
print(low, high) # 64 95
print(min_max([5, 9])) # (5, 9)
Read more: the official tutorial on defining functions.
Done here? The practice set for Part 5 โ 8 exercises with solutions โ is on the part page.