Learn Python · lesson 34 of 60 · about 7 minutes
Return Values and Defaults
Price the basket: functions that return an answer instead of printing it, and a discount that defaults to none.
What you'll learn
- Return a value
- Use a returned value
- Give parameters defaults
Prices, with and without a code
The assistant needs the basket's price twice: the normal price, and the price with a discount code. basket_cost(items, discount=0) adds up the prices and returns the total in pence instead of printing it, so the program can use it however it likes, and pounds(pence) returns it as text like £5.80. Leaving out the discount uses the default, 0.
return sends a result back
print shows something on the screen. return hands a value back to whoever called the function, so you can store it or use it in more calculations.
return also ends the function straight away. A function with no return gives back None.
Using a returned value
def double(n):
return n * 2
result = double(5)
print(result + 1)
print(double(double(3)))Output
11
12Default values
A parameter can have a default with =. If the caller leaves it out, the default is used.
A default tip percentage
def tip(bill, percent=10):
return bill * percent / 100
print(tip(50))
print(tip(50, 20))Output
5.0
10.0Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.