Calling Functions from Functions

Calling Functions from Functions

A function body can call other functions. This splits a computation into named steps:

def apply_discount(price):
    return price * 0.9

def final_price(price, quantity):
    return apply_discount(price) * quantity

print(final_price(100, 2))

Output:

180.0

final_price called apply_discount, used its return value, and returned the result. Each function does one thing; the higher-level function combines them.

This is the main way programs grow: small functions that each handle one step, combined by functions above them.

Exercise

The starter code defines to_cents — it converts dollars to cents (1 dollar = 100 cents).

  1. Define a function named total_in_cents with two parameters: price_in_dollars and quantity.
  2. It returns the total in cents. Call to_cents inside the body — do not write * 100 yourself.

For example, total_in_cents(3, 2) returns 600.

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

Tests

import unittest


class TestTotalInCents(unittest.TestCase):
    def test_3_dollars_twice_is_600_cents(self):
        self.assertEqual(total_in_cents(3, 2), 600)

    def test_12_dollars_once_is_1200_cents(self):
        self.assertEqual(total_in_cents(12, 1), 1200)

    def test_zero_quantity_is_zero(self):
        self.assertEqual(total_in_cents(5, 0), 0)
def to_cents(dollars):
    return dollars * 100


def total_in_cents(price_in_dollars, quantity):
    return to_cents(price_in_dollars) * quantity


print(total_in_cents(3, 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.