Implementing Number to Words Conversion in Python Without Using the num2word Library

Dec 02, 2025 · Programming · 11 views · 7.8

Keywords: Python | Number to Words | divmod Function | Conditional Statement Optimization | Programming Best Practices

Abstract: This paper explores methods for converting numbers to English words in Python without relying on third-party libraries. By analyzing common errors such as flawed conditional logic and improper handling of number ranges, an optimized solution based on the divmod function is proposed. The article details how to correctly process numbers in the range 1-99, including strategies for special numbers (e.g., 11-19) and composite numbers (e.g., 21-99). Through code restructuring, it demonstrates how to avoid common pitfalls and enhance code readability and maintainability.

Problem Background and Common Error Analysis

In Python programming, converting numbers to their corresponding English words is a common requirement, particularly in natural language processing or user interface development. Although third-party libraries like num2word exist, developers may need to implement this functionality themselves under certain constraints. This paper addresses a typical scenario: converting numbers from 1 to 99 into English words, analyzing errors in the original code, and providing an optimized solution.

Diagnosis of Issues in the Original Code

The main issue in the original code lies in logical errors in conditional statements. For example, the condition if (Number > 1) or (Number < 19): is almost always true, as most numbers satisfy at least one of the subconditions Number > 1 or Number < 19. This causes only the first if block to execute, while the elif and else blocks are ignored. Correct logic should use the and operator or chained comparisons to limit the number range, e.g., if 1 <= Number <= 19:.

Core Concepts of the Optimized Solution

Inspired by the best answer (Answer 3), we propose an optimized solution. This approach uses two dictionaries: one for storing words of special numbers from 1 to 19, and another for tens from 20 to 90. Key steps include:

  1. Using chained comparisons to correctly define number ranges.
  2. For numbers from 20 to 99, utilizing the divmod() function to obtain tens and units digits.
  3. Deciding whether to add a hyphen and the units digit word based on if the remainder is zero.

Below is a refactored code example:

num2words1 = {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 
            6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'}
num2words2 = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']

def number_to_words(Number):
    if 0 <= Number <= 19:
        return num2words1[Number]
    elif 20 <= Number <= 99:
        tens, remainder = divmod(Number, 10)
        if remainder == 0:
            return num2words2[tens - 2]
        else:
            return num2words2[tens - 2] + '-' + num2words1[remainder]
    else:
        return 'Number out of range'

# Test examples
print(number_to_words(0))   # Output: Zero
print(number_to_words(13))  # Output: Thirteen
print(number_to_words(42))  # Output: Forty-Two
print(number_to_words(99))  # Output: Ninety-Nine

Code Explanation and Extended Discussion

In the above code, divmod(Number, 10) returns a tuple where the first element is the tens digit (e.g., 4 for 42) and the second is the units digit (e.g., 2). The expression tens - 2 indexes the num2words2 list, as list indices start at 0 corresponding to 'Twenty'. For non-zero units digits, a hyphen connects the tens and units words, adhering to English writing conventions (e.g., 'Forty-Two').

Other answers provide supplementary insights. For instance, Answer 2 uses a single dictionary and exception handling to simplify the code but may sacrifice some readability. Answer 4 presents a more general solution supporting larger number ranges (e.g., thousands, millions), albeit with higher complexity. In practice, developers should balance conciseness and extensibility based on requirements.

Conclusion and Best Practice Recommendations

When implementing number-to-words conversion, it is advisable to follow these best practices:

Through the solution presented in this paper, developers can efficiently and accurately convert numbers from 1 to 99 into English words without third-party libraries, laying a foundation for more complex natural language processing tasks.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.