Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print Digits in Words

Print each decimal digit as an English word using recursion. Students delay output until smaller prefixes return and handle zero as a complete input separately.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 7 of 10
print-digits-in-words.py
1def print_digit_word(digit):
2 words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
3 return words[digit]
4
5def digits_in_words(n):
6 # Base case
7 if n == 0:
8 return
9
10 # Recursive case
11 digits_in_words(n // 10)
12 digit = n % 10
13 print(print_digit_word(digit), end=" ")
14
15# Test
16num = int(input("Enter a number: "))
17if num == 0:
18 print(print_digit_word(0), end=" ")
19else:
20 digits_in_words(abs(num))
21print()

Output

Enter a number: 123
One Two Three

In this one

  • Delay digit output
  • Map digits through a list
  • Print a literal zero separately

How it works

  1. 1

    For literal zero, print the zero-word mapping directly.

  2. 2

    Otherwise recurse on the remaining prefix first.

  3. 3

    Map and print the current digit as calls return.

Edge cases

Does the zero inside 105 print?

Does the zero inside 105 print?

Yes. It is processed after the prefix call returns.

Why special-case input zero?

Why special-case input zero?

The helper would otherwise return without printing any word.

What's going on

digits_in_words first calls itself on n // 10. It then maps n % 10 through the ten-word list, so output follows the original left-to-right digit order.

The zero base case means an exhausted prefix, not the word Zero. For input 105, the interior zero still prints during return. A literal zero input needs its own call to the word mapper. The call stack preserves pending digits.

Does the zero inside 105 print? Yes. It is processed after the prefix call returns.

Why special-case input zero? The helper would otherwise return without printing any word.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why recurse before printing?

Pick an answer to check it.

Question 2

Does the zero inside 105 print?

Pick an answer to check it.

Questions people ask

Does the zero inside 105 print?

Yes. It is processed after the prefix call returns.

Why special-case input zero?

The helper would otherwise return without printing any word.

Why recurse before printing?

To print the most significant digit first.