Editor

Readable Durations

Advanced · Stretch · from Python Functions: Define, Call, and Return Values

From the lesson: Python Functions: Define, Call, and Return Values

Imagine you have a favorite recipe for pancakes. Every Sunday morning, you follow the same steps: mix flour, crack eggs, pour batter, flip. You don't reinvent the recipe each time - you just follow the one you already know.

Read the lesson

Write a function describe_duration(seconds) that turns a whole number of seconds into text a person can read:

describe_duration(3725)   # '1 hour, 2 minutes and 5 seconds'
describe_duration(120)    # '2 minutes'

The rules:

  • Use hours, minutes and seconds (no days: 90,000 seconds is 25 hours). Leave out any unit that is zero.
  • Write 1 hour, 1 minute, 1 second for one, and add an s for any other number.
  • Join the last two parts with " and " and any others with ", ".
  • 0 seconds is "now".
  • A small helper function for the singular and plural will keep your main function short. Some of the tests are hidden.

    def describe_duration(seconds):
    pass
    Solution unlocks after your first Check

    What Check runs

    Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

    RunsExpected output
    describe_duration(3725)'1 hour, 2 minutes and 5 seconds'
    describe_duration(120)'2 minutes'

    More Function exercises

    All Python exercises · 50 practice problems · Functions quiz