TheAlgorithms/Python · error · ValueError

Please enter a valid number

Error message

Please enter a valid number

What it means

Raised by decimal_to_fraction() in maths/decimal_to_fraction.py when its argument cannot be converted to a float. The function immediately does float(decimal) inside a try/except ValueError and re-raises ValueError with this clearer message; accepted inputs include numbers and numeric strings like '1.23e2' and '0.500'.

Source

Thrown at maths/decimal_to_fraction.py:37

    >>> decimal_to_fraction(0)
    (0, 1)
    >>> decimal_to_fraction(-2.5)
    (-5, 2)
    >>> decimal_to_fraction(0.125)
    (1, 8)
    >>> decimal_to_fraction(1000000.25)
    (4000001, 4)
    >>> decimal_to_fraction(1.3333)
    (13333, 10000)
    >>> decimal_to_fraction("1.23e2")
    (123, 1)
    >>> decimal_to_fraction("0.500")
    (1, 2)
    """
    try:
        decimal = float(decimal)
    except ValueError:
        raise ValueError("Please enter a valid number")
    fractional_part = decimal - int(decimal)
    if fractional_part == 0:
        return int(decimal), 1
    else:
        number_of_frac_digits = len(str(decimal).split(".")[1])
        numerator = int(decimal * (10**number_of_frac_digits))
        denominator = 10**number_of_frac_digits
        divisor, dividend = denominator, numerator
        while True:
            remainder = dividend % divisor
            if remainder == 0:
                break
            dividend, divisor = divisor, remainder
        numerator, denominator = numerator // divisor, denominator // divisor
        return numerator, denominator


if __name__ == "__main__":

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate/clean the string before calling: strip currency symbols and commas, reject empty values.
  2. If the input may be a fraction string like '1/2', parse it yourself with fractions.Fraction instead.
  3. Consider using fractions.Fraction(str_value) directly — it handles decimals and fraction strings and reduces automatically.

Example fix

# before
decimal_to_fraction('1/2')  # ValueError: Please enter a valid number

# after
from fractions import Fraction
Fraction('1/2')  # Fraction(1, 2)
# or: decimal_to_fraction(float(user_str)) after validating user_str
Defensive patterns

Strategy: try-catch

Validate before calling

try:
    value = float(str(user_input).strip())
except ValueError:
    raise ValueError(f'not a parseable decimal: {user_input!r}') from None

Type guard

def is_parseable_decimal(v) -> bool:
    try:
        float(v)
        return True
    except (TypeError, ValueError):
        return False

Try / catch

try:
    num, den = decimal_to_fraction(raw)
except ValueError as e:
    if 'valid number' in str(e):
        raw = raw.replace(',', '.').strip()  # locale fix, then retry once
        num, den = decimal_to_fraction(raw)
    else:
        raise

Prevention

When it happens

Trigger: Calling decimal_to_fraction('abc'), decimal_to_fraction(None), decimal_to_fraction(''), or any string float() rejects. Note float('nan')/float('inf') parse fine and will misbehave later instead.

Common situations: Unvalidated user or CSV input ('1,5' with a comma, '1/2' as a fraction string, empty cells, currency symbols); None from an optional field; strings with surrounding whitespace actually work, but non-numeric text does not.

Related errors


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