The Price of a Line

A receipt also shows how much each line costs: the price of one piece times the quantity. Two loaves of bread at $3 each cost $6.

You'll compute this in a new function, line_total(item). It gets one item (one dictionary) and returns the price of its line with return. Why write a function for a single multiplication? You'll need the price of a line in two places: on the receipt, and in the next exercise, when you add up the whole order. And a good name tells you what the code means: line_total(item) is easier to understand than item["price"] * item["quantity"].

Remember the difference between return and print(): print() only shows a value, while return gives it back to the code that called the function, which can then work with it. For example, you can call a function right inside the braces of an f-string:

def double(number):
    return number * 2


print(f"Twice 4 is {double(4)}")
Twice 4 is 8

If double() printed the result instead of returning it, the program would print 8 on a line of its own, and the f-string would get None, which is what a function without return gives back: Twice 4 is None.

Keep all the functions together, between the data at the top and the call at the bottom. Write the new one above print_receipt(), which will use it.

Instructions

Under the data (above print_receipt()), write a function line_total(item) that returns the price of one piece of the item times its quantity.

In print_receipt(), add the price of the line, computed by line_total(), to the end of each line: Bread: 2 x $3 = $6.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/7