Introduction
In this tutorial, we will walk you through a Python program that converts a numerical input into its corresponding word representation. Whether it’s converting simple integers or large numbers, this tool can help transform digits into a readable text format. This is particularly useful for applications like writing cheques, displaying amounts in words, or simply for educational purposes.
Objective
The objective of this program is to convert any given number (integer) into its word form. This program can handle numbers of varying sizes, including those with multiple digits, and outputs them in a readable and understandable format, such as “One Hundred and Twenty-Five” for 125.
Python Code: Number to Words Converter
def number_to_words(n): ones = ["", "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"] thousands = ["", "Thousand", "Million", "Billion", "Trillion"] def helper(n, index): if n == 0: return "" elif n < 20: return ones[n] + " " elif n < 100: return tens[n // 10] + " " + helper(n % 10, 0) else: return ones[n // 100] + " Hundred " + helper(n % 100, 0) if n == 0: return "Zero" result = "" index = 0 while n > 0: if n % 1000 != 0: result = helper(n % 1000, index) + thousands[index] + " " + result n //= 1000 index += 1 return result.strip() # Example usage: num = int(input("Enter a number: ")) print(f"Number in words: {number_to_words(num)}")
Program Explanation
This Python program uses a recursive helper function to break down the number into smaller parts and then convert them into words. Here’s how it works:
- The program starts by checking the number and splits it into groups of three digits (e.g., thousands, millions, billions).
- For each group, the program converts the number into words using the
helper
function, which handles numbers from 1 to 999. - The
helper
function checks if the number is less than 20, less than 100, or greater than 100, and appropriately converts it to words. - The main
number_to_words
function iterates through each group of thousands, and appends the respective suffix (like “Thousand”, “Million”, etc.) to each part. - The final result is the concatenation of all parts, giving a complete word representation of the number.
How to Run the Program
To run this Python program on your machine, follow these steps:
- Ensure you have Python installed on your system. You can download it from python.org.
- Copy the code provided above into a new Python file (e.g.,
number_to_words.py
). - Open your command-line interface (Terminal, Command Prompt, etc.) and navigate to the directory where the file is saved.
- Run the program by typing
python number_to_words.py
and hitting Enter. - Input a number when prompted, and the program will output the word representation of the number.