Print Digits in Words
Print digits of a number in words recursively.
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]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: "))17digits_in_words(abs(num))18print()
Output
Enter a number: 123 One Two Three
What's going on
Recurse first, then print current digit.
Key Concepts:
Recurse on remaining digits first
Print current digit word after recursion
Processes digits left to right
🔗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