Python Functions Tutorial: def, return, Arguments and lambda with Examples
P7.2 How to Use return in a Python Function
Why. Printing shows a value to you, but the program cannot use it. return gives the value back so you can store it, add it or put it in a column.
What. return value ends the function and sends the value back to the caller.
How.
Return a result
- Calculate the answer inside the function.
- Write
return answer. - Store the call in a variable:
x = my_func(...).
Worked example A — Add VAT.
Step 1 — What we do. A UK shop adds 20% VAT.
Step 2 — Type and run this code.
def add_vat(price):
return price * 1.20
print(add_vat(100))
total = add_vat(50) + add_vat(25)
print(total)
Step 3 — Output you should see.
120.0
90.0
Step 4 — What it means. The returned value can be printed or used in more maths.
Worked example B — print vs return.
Step 1 — What we do. We compare a function that prints with one that returns.
Step 2 — Type and run this code.
def show(x):
print(x * 2)
def give(x):
return x * 2
a = show(5)
b = give(5)
print(a, b)
Step 3 — Output you should see.
10
None 10
Step 4 — What it means. show printed 10 but returned nothing, so a is None. give returned 10. Use return when the result is needed later.
Worked example C — Return early.
Step 1 — What we do. A bank fee function returns 0 for premium customers.
Step 2 — Type and run this code.
def monthly_fee(balance, is_premium):
if is_premium:
return 0
if balance < 1000:
return 5
return 2
print(monthly_fee(500, False))
print(monthly_fee(500, True))
print(monthly_fee(5000, False))
Step 3 — Output you should see.
5
0
2
Step 4 — What it means. The first return that runs ends the function.
Ravindra Bagale's Tip
Most of your data functions should return, not print. Print only at the end to show results.
Ravindra Bagale's Tip – मराठी
तुमची बहुतेक data functions print नव्हे, return करायला हवीत. Results दाखवायला शेवटीच print करा.
Ravindra Bagale's Tip – हिंदी
आपके ज़्यादातर data functions print नहीं, return करें. Results दिखाने के लिए आख़िर में ही print करो.