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.
1def print_digit_word(digit):2 words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]3 return words[digit]45def digits_in_words(n):6 # Base case7 if n == 0:8 return910 # Recursive case11 digits_in_words(n // 10)12 digit = n % 1013 print(print_digit_word(digit), end=" ")1415# Test16num = 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
For literal zero, print the zero-word mapping directly.
- 2
Otherwise recurse on the remaining prefix first.
- 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.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum