Integer to words

MediumFunction Programs · 38 of 39

Write a Python function that converts an integer from 0 to 999 into English words.

Advertisement
Input
0, 15, 42, 305, 999
Output
0 -> zero
15 -> fifteen
42 -> forty-two
305 -> three hundred and five
999 -> nine hundred and ninety-nine

Approach

  1. Handle hundreds, then tens, then units with lookup lists.

Solution

Python
ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",        "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",        "seventeen", "eighteen", "nineteen"]TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] def to_words(n):    if n < 20:        return ONES[n]    if n < 100:        return TENS[n // 10] + ("" if n % 10 == 0 else "-" + ONES[n % 10])    rest = n % 100    return ONES[n // 100] + " hundred" + ("" if rest == 0 else " and " + to_words(rest)) for n in [0, 15, 42, 305, 999]:    print(n, "->", to_words(n))
Output
0 -> zero
15 -> fifteen
42 -> forty-two
305 -> three hundred and five
999 -> nine hundred and ninety-nine

Line by line

Lines 7-8

Numbers below 20 have their own names.

Lines 9-10

Tens plus an optional unit, joined with a hyphen.

Lines 11-12

Hundreds reuse the same function for the remainder.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs