Python Program to Convert a Number to Words
Intermediate · Numbers
This program writes a number out in English words, the way an amount is written on a cheque: 45207 becomes forty-five thousand two hundred seven. It works for every whole number from 0 to 999999 by splitting the number into thousands and the rest.
Program
45,207 in words: forty-five thousand two hundred seven
How it works
- The numbers 0 to 19 all have their own names, so they sit in the
oneslist, andtensholds twenty, thirty and so on. below_thousand()writes 1 to 999: the hundreds digit first, then either a tens word with a hyphen, like forty-five, or a single word for anything below 20.- Any number up to 999999 splits into
num // 1000, the thousands, andnum % 1000, the rest, and the same function writes both parts. .strip()removes the extra space left at the end of round numbers like 5000, and{num:,}prints the number with a comma.
Other ways to write it
Digit by digit
45207 -> four five two zero seven
Some exercises only ask for each digit as a word, which a lookup list does in a single line.
In the Indian system, with lakh
125000: one lakh twenty-five thousand 4570890: forty-five lakh seventy thousand eight hundred ninety 999: nine hundred ninety-nine
Indian numbering groups digits as thousands, then lakhs (1,00,000), so 125000 is one lakh twenty-five thousand. The loop takes each place out with // and %, largest first.
Try it yourself
Try 0, 19, 100, 1000 and 999999 to check that every branch of the program gives the right words.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises