Lesson 16 · 16 of 20
Parameters, defaults and return · Python
Give default values to the parameters of your Python functions, call them by name and send back several results with return.

A function can have several parameters. In order_total(price, quantity, discount=0) the last one has a default value: if you leave it out, it is 0. That is why order_total(4.0, 3) gives 12.0, while order_total(4.0, 3, 25) takes 25 % off and gives 9.0.
You can also pass values by name (keyword arguments): order_total(quantity=2, price=10.0, discount=10). Then the order does not matter and the call reads better.
return can give back several values separated by commas: what it really returns is a tuple. summary() returns the lowest mark, the highest and the average, and the call unpacks them into low, high, avg, just as you did with tuples.
return also ends the function right there. In grade(), if the mark is 9 or more it returns «Outstanding» and never looks at the rest, so there is no need for elif or else.
A function without return gives back None («nothing»). cheer() prints its sentence, but what it returns is None, and that is what the last print() shows.
Code · main.py
# Several parameters; the last one has a default value.def order_total(price, quantity, discount=0): total = price * quantity return total - total * discount / 100print(order_total(4.0, 3)) # no discountprint(order_total(4.0, 3, 25)) # 25 % offprint(order_total(quantity=2, price=10.0, discount=10)) # by name# return can give back several values at once (a tuple).def summary(marks): average = sum(marks) / len(marks) return min(marks), max(marks), round(average, 1)low, high, avg = summary([6, 9, 7, 10, 8])print(f"Lowest {low}, highest {high}, average {avg}")# return also ends the function straight away.def grade(mark): if mark >= 9: return "Outstanding" if mark >= 5: return "Pass" return "Keep trying"for mark in [9.5, 7.2, 5.0, 3.8]: print(mark, "->", grade(mark))# A function without return gives back None.def cheer(name): print("Well done,", name)print(cheer("Lola"))Output · python3 main.py
12.0 9.0 18.0 Lowest 6, highest 10, average 8.0 9.5 -> Outstanding 7.2 -> Pass 5.0 -> Pass 3.8 -> Keep trying Well done, Lola None
Key points
param=valuegives a default value.- Keyword arguments can go in any order.
return a, breturns a tuple you can unpack.returnleaves the function at once.- Without
return, a function returnsNone.
Exercise
Add a shipping=3.5 parameter to order_total() that is added at the end, unless the total is over 30 euros (then shipping is free).