Want to convert numbers to words in Python? This beginner-friendly project will teach you how to transform numerical values into their written English equivalents using Python functions, loops, and conditionals.
What You Will Learn:
- Handling number conversions with indexing
- Using tuple-based lookup tables for efficiency
- Formatting large numbers with suffixes
- Working with conditionals and loops
- Structuring Python functions for clean code
Step 1: Setting Up the Project
Before we start coding, let’s set up our Python project:
1. Make sure Python is installed on your computer. If not, download it from the official Python website.
2. Open your favorite code editor or IDE.
3. Create a new Python file, for example, number_to_words.py
.
Great, now, let's dive head first into our Python editor to get this build started.
Step 2: How the Numbers to Words Converter Works
Our Numbers to Words Converter will:
- Accept an integer input from the user.
- Convert it into words following English grammar rules.
- Support numbers up to 12 digits long (trillions).
- Use tuples to efficiently look up number names.
By the end of this tutorial, we should have something like I've shown below:
Step 3: Defining Lookup Tables
To get started, we need to define essential lookup tables for number names using the Python tuple.
ones = (
'Zero', 'One', 'Two', 'Three', 'Four',
'Five', 'Six', 'Seven', 'Eight', 'Nine'
)
twos = (
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen',
'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
)
tens = (
'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty',
'Seventy', 'Eighty', 'Ninety', 'Hundred'
)
suffixes = (
'', 'Thousand', 'Million', 'Billion'
)
How It Works:
-
Stores predefined number names for efficient lookup.
-
Uses tuples instead of lists because tuples are immutable and faster.
-
Categorizes numbers into
ones
,twos
, andtens
for easy retrieval. -
Defines suffixes (
Thousand
,Million
,Billion
) to structure large numbers correctly.
Why Use Tuples Instead of Lists?
-
Tuples are immutable → Prevents accidental modifications.
-
Faster lookup → Tuples use less memory than lists.
-
Easier management → Organizing numbers in tuples makes the code cleaner.
By structuring our number names this way, we ensure fast and error-free number conversion. Now, let's move on to processing number segments.
Step 4: Writing the Number Conversion Function
We’ll define a function called fetch_words() to extract words for each three-digit segment.
def fetch_words(number):
"""Converts a three-digit segment into words."""
number = number.zfill(3) # Ensure three-digit format
hundreds_digit = int(number[0])
tens_digit = int(number[1])
ones_digit = int(number[2])
words = []
if hundreds_digit > 0:
words.append(ones[hundreds_digit])
words.append("Hundred")
if tens_digit > 1:
words.append(tens[tens_digit - 2])
if ones_digit > 0:
words.append(ones[ones_digit])
elif tens_digit == 1:
words.append(twos[ones_digit])
elif ones_digit > 0:
words.append(ones[ones_digit])
return " ".join(words)
How It Works:
-
Ensures numbers are processed in three-digit segments using
zfill(3)
, which pads numbers with leading zeros if necessary. -
Handles the hundreds place by checking if the first digit is greater than zero.
-
Processes the tens and ones places:
-
If the tens digit is
1
, it fetches the word fromtwos
(e.g.,15 → Fifteen
). -
If the tens digit is
2
or more, it fetches fromtens
and appends the correctones
digit (e.g.,23 → Twenty-Three
). -
If the tens digit is
0
, only theones
digit is considered.
-
-
Uses
append()
to dynamically build the word list:-
Each word is added sequentially, ensuring the correct order.
-
Prevents unnecessary operations by only adding non-empty values.
-
-
Uses
" ".join(words)
to create a readable output:-
Joins all words in the list with a space between them.
-
Ensures a clean, properly formatted string for final output.
-
Why Break Numbers into Three-Digit Segments?
-
Aligns with English grammar rules → Numbers are typically spoken in groups of three (
One Hundred Twenty-Three Million
). -
Simplifies large number handling → Allows conversion of large numbers in manageable parts.
-
Ensures readability → Outputs structured number names without confusion.
By structuring our function this way, we ensure accurate, readable, and efficient number conversion. Now, let’s process full numbers
Step 5: Handling Full Number Conversion
We'll create a convert_to_words() function to process the entire number.
def convert_to_words(number):
"""Converts a full number into words with correct suffixes."""
str_num = str(number)
length = len(str_num)
if length > 12:
return 'This program supports a maximum of 12-digit numbers.'
# Split number into three-digit chunks from right to left
num_segments = []
while length > 0:
num_segments.append(str_num[max(0, length - 3):length])
length -= 3
words = []
for idx, segment in enumerate(num_segments):
segment_words = fetch_words(segment)
if segment_words:
words.append(segment_words + (' ' + suffixes[idx] if idx > 0 else ''))
return " ".join(reversed(words)).strip()
How It Works:
-
Converts the number to a string to allow easy segmentation.
-
Splits the number into three-digit segments from right to left.
-
Uses a loop to extract and process each segment independently via the Python enumerate function.
-
Calls
fetch_words()
to convert each three-digit segment into words. -
Appends the appropriate suffix (
Thousand
,Million
,Billion
) to each segment. -
Uses
.join(reversed(words))
to construct the final output:-
Ensures segments appear in the correct order.
-
Prevents trailing spaces for clean formatting.
-
Why Process the Number in Segments?
-
Follows standard English number formatting → Large numbers are broken into manageable parts.
-
Ensures consistent conversion logic → Keeps the conversion function simple and scalable.
-
Improves readability → Outputs structured number names clearly.
By structuring our function this way, we ensure accurate, readable, and efficient number conversion. Now, let’s finalize the program execution.
Step 6: Running the Program
We’ll add user interaction to take input and display the converted words.
if __name__ == '__main__':
number = int(input('Enter any number: '))
print(f'{number} in words is: {convert_to_words(number)}')
How It Works:
-
Uses
if __name__ == '__main__'
to ensure the script runs only when executed directly. -
Prompts the user to enter a number.
-
Passes the input number to
convert_to_words()
, which processes and returns the words. -
Prints the final output to display the number in words via a Python f-string.
Why Use if __name__ == '__main__'
?
-
Prevents unintended execution when the script is imported as a module.
-
Keeps the main logic separate, making the program more maintainable and modular.
-
Ensures proper script execution flow by handling user input and function calls in sequence.
By structuring our program execution this way, we ensure that the user can interact with the converter seamlessly. Now, your Python Numbers to Words Converter is fully functional.
Final Code: Number to Words Converter
# Numbers to Words Converter in Python
# Lookup tables for number names
ones = (
'Zero', 'One', 'Two', 'Three', 'Four',
'Five', 'Six', 'Seven', 'Eight', 'Nine'
)
twos = (
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen',
'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
)
tens = (
'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty',
'Seventy', 'Eighty', 'Ninety'
)
suffixes = (
'', 'Thousand', 'Million', 'Billion'
)
def fetch_words(number):
"""Converts a three-digit segment into words."""
number = number.zfill(3) # Ensure three-digit format
hundreds_digit = int(number[0])
tens_digit = int(number[1])
ones_digit = int(number[2])
words = []
if hundreds_digit > 0:
words.append(ones[hundreds_digit])
words.append("Hundred")
if tens_digit > 1:
words.append(tens[tens_digit - 2])
if ones_digit > 0:
words.append(ones[ones_digit])
elif tens_digit == 1:
words.append(twos[ones_digit])
elif ones_digit > 0:
words.append(ones[ones_digit])
return " ".join(words)
def convert_to_words(number):
"""Converts a full number into words with correct suffixes."""
str_num = str(number)
length = len(str_num)
if length > 12:
return 'This program supports a maximum of 12-digit numbers.'
# Split number into three-digit chunks from right to left
num_segments = []
while length > 0:
num_segments.append(str_num[max(0, length - 3):length])
length -= 3
words = []
for idx, segment in enumerate(num_segments):
segment_words = fetch_words(segment)
if segment_words:
words.append(segment_words + (' ' + suffixes[idx] if idx > 0 else ''))
return " ".join(reversed(words)).strip()
if __name__ == '__main__':
number = int(input('Enter any number: '))
print(f'{number} in words is: {convert_to_words(number)}')
Wrapping Up
Congratulations! You’ve built a fully functional Python program that converts numbers into words.
What You Learned:
- Using tuples for efficient lookups
- Formatting numbers into three-digit segments
- Applying suffixes for large numbers
- Handling user input for real-time conversion
Next Steps:
- Add support for currency conversion (e.g., $1,234 → One Thousand Two Hundred Thirty-Four Dollars
).
- Improve handling of negative numbers (-123 → Negative One Hundred Twenty-Three
).
- Build a GUI version using Tkinter for a better user experience.
The best way to learn Python is by building real projects—so keep experimenting!