TheAlgorithms/Python · error · ValueError

This function only converts numbers less than 100

Error message

This function only converts numbers less than 100

What it means

convert_small_number raises this ValueError when num >= 100. The helper only builds words for 0-99 (two tables indexed by tens and ones digits), so three-digit numbers would index the TENS table out of range or produce wrong output; the guard makes the contract explicit. Larger numbers must go through convert_number, which splits them into power-of-ten digit groups.

Source

Thrown at conversions/convert_number_to_words.py:124

    >>> convert_small_number(15)
    'fifteen'
    >>> convert_small_number(20)
    'twenty'
    >>> convert_small_number(25)
    'twenty-five'
    >>> convert_small_number(-1)
    Traceback (most recent call last):
    ...
    ValueError: This function only accepts non-negative integers
    >>> convert_small_number(123)
    Traceback (most recent call last):
    ...
    ValueError: This function only converts numbers less than 100
    """
    if num < 0:
        raise ValueError("This function only accepts non-negative integers")
    if num >= 100:
        raise ValueError("This function only converts numbers less than 100")
    tens, ones = divmod(num, 10)
    if tens == 0:
        return NumberWords.ONES.value[ones] or "zero"
    if tens == 1:
        return NumberWords.TEENS.value[ones]
    return (
        NumberWords.TENS.value[tens]
        + ("-" if NumberWords.ONES.value[ones] else "")
        + NumberWords.ONES.value[ones]
    )


def convert_number(
    num: int, system: Literal["short", "long", "indian"] = "short"
) -> str:
    """
    Converts an integer to English words.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use convert_number(123) which delegates to this helper correctly
  2. Range-check inputs: assert 0 <= num < 100 before calling
  3. If writing a similar helper, decompose hundreds first: divmod(num, 100)

Example fix

# before
convert_small_number(123)
# ValueError: This function only converts numbers less than 100

# after
convert_number(123)  # 'one hundred twenty-three'
Defensive patterns

Strategy: validation

Validate before calling

if not 0 <= num < 100:
    raise ValueError('convert_small_number accepts 0..99 only')

Type guard

def is_small_non_negative(n) -> bool:
    return isinstance(n, int) and 0 <= n < 100

Try / catch

try:
    convert_small_number(n)
except ValueError:
    return convert_number(n)

Prevention

When it happens

Trigger: convert_small_number(123); convert_small_number(100) exactly at the boundary; helper invoked recursively without convert_number's digit-group splitting.

Common situations: Using the helper as a general number-to-words function; copy-pasting the doctest call while adjusting the example value upward.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/3bd418bdd32fe4fb. Report an issue: GitHub.