A sales calculation returns the total and the discount as a pair.
What You Need to Understand
A function can return a tuple of related values, and the caller can unpack them into meaningful variables. This avoids storing intermediate results in unrelated global variables.
When to Use It
A sales calculation returns the total and the discount as a pair.
Step-by-Step Python Example
def calculate_total(price, discount_rate):
discount_amount = price * discount_rate
return price - discount_amount, discount_amount
final_price, discount = calculate_total(80, 0.1)
print(final_price)
print(discount)
How the Example Works
The function returns one two-item tuple; unpacking assigns its parts to the two names.
Example Output
72.0
8.0
(2, 7)
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
def bounds(values):
return min(values), max(values)
print(bounds([3, 7, 2]))
Important Behavior and Edge Cases
The caller must expect the correct number of returned values. Use a named record when many fields could make positional meanings unclear.
Try It Yourself
Write a function returning both the minimum and maximum of a nonempty list.
Common Beginner Mistakes
- The caller must expect the correct number of returned values. Use a named record when many fields could make positional meanings unclear.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- A function can return a tuple of related values, and the caller can unpack them into meaningful variables.
- The function returns one two-item tuple; unpacking assigns its parts to the two names.
- The caller must expect the correct number of returned values.