Practice: Receipt Line

Practice: Receipt Line

This exercise combines the section: two functions, one calling the other, multiple parameters, and an f-string.

Exercise

  1. Define a function named line_total with two parameters, price and quantity. It returns their product.
  2. Define a function named receipt_line with three parameters: item, price, and quantity. It returns an f-string in the form:

<item>: <quantity> x <price> = <total>

where <total> comes from calling line_total.

For example, receipt_line("pen", 3.0, 2) returns "pen: 2 x 3.0 = 6.0".

Run your code to see the output, then press Submit.

Hints

  • Write and check line_total first — it is one line.
  • Inside receipt_line, call line_total(price, quantity) inside the braces of the f-string, or store it in a variable first.
  • Watch the order in the output: quantity before price.

Tests

import unittest


class TestReceiptLine(unittest.TestCase):
    def test_line_total_multiplies_price_by_quantity(self):
        self.assertAlmostEqual(line_total(3.0, 2), 6.0)

    def test_line_total_with_zero_quantity(self):
        self.assertAlmostEqual(line_total(9.5, 0), 0.0)

    def test_receipt_line_for_two_pens(self):
        self.assertEqual(receipt_line("pen", 3.0, 2), "pen: 2 x 3.0 = 6.0")

    def test_receipt_line_for_three_notebooks(self):
        self.assertEqual(receipt_line("notebook", 4.5, 3), "notebook: 3 x 4.5 = 13.5")
def line_total(price, quantity):
    return price * quantity


def receipt_line(item, price, quantity):
    total = line_total(price, quantity)
    return f"{item}: {quantity} x {price} = {total}"


print(receipt_line("pen", 3.0, 2))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.