TheAlgorithms/Python · error · ValueError

Non-binary value was passed to the function

Error message

Non-binary value was passed to the function

What it means

bin_to_decimal raises this ValueError when any character of the (possibly negative) input is not '0' or '1'. A leading '-' is allowed and stripped first, so '-101' is valid while '39', '10a1', or '-1-0' are rejected. The parser is character-by-character Horner-style, so it must reject non-binary digits before looping.

Source

Thrown at conversions/binary_to_decimal.py:33

        ...
    ValueError: Non-binary value was passed to the function
    >>> bin_to_decimal("")
    Traceback (most recent call last):
        ...
    ValueError: Empty string was passed to the function
    >>> bin_to_decimal("39")
    Traceback (most recent call last):
        ...
    ValueError: Non-binary value was passed to the function
    """
    bin_string = str(bin_string).strip()
    if not bin_string:
        raise ValueError("Empty string was passed to the function")
    is_negative = bin_string[0] == "-"
    if is_negative:
        bin_string = bin_string[1:]
    if not all(char in "01" for char in bin_string):
        raise ValueError("Non-binary value was passed to the function")
    decimal_number = 0
    for char in bin_string:
        decimal_number = 2 * decimal_number + int(char)
    return -decimal_number if is_negative else decimal_number


if __name__ == "__main__":
    from doctest import testmod

    testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Strip the 0b prefix before calling: s.removeprefix('0b')
  2. Sanitize with a regex: re.fullmatch(r'-?[01]+', s)
  3. For arbitrary-base strings, use int(s, 2) which handles 0b prefixes and whitespace itself

Example fix

# before
bin_to_decimal(bin(5))  # '0b101'
# ValueError: Non-binary value was passed to the function

# after
bin_to_decimal(bin(5).removeprefix('0b'))
# or simply: int(bin(5), 2)
Defensive patterns

Strategy: type-guard

Validate before calling

import re
if not re.fullmatch(r'-?[01]+', bin_string.strip()):
    raise ValueError(f'not a binary string: {bin_string!r}')

Type guard

def is_binary_string(s: str) -> bool:
    s = s.strip().removeprefix('-')
    return s != '' and all(c in '01' for c in s)

Try / catch

try:
    bin_to_decimal(s)
except ValueError as e:
    if 'Non-binary' in str(e):
        return int(s, 2) if re.fullmatch(r'-?[0-9]+', s or '') else None
    raise

Prevention

When it happens

Trigger: bin_to_decimal('39'), bin_to_decimal('10O1') (letter O instead of zero), bin_to_decimal('0b101') — the '0b' prefix is not stripped and 'b' fails the check, bin_to_decimal('1 01') with an interior space.

Common situations: Passing Python repr output like bin(5) -> '0b101' directly; OCR/typo artifacts (O vs 0, l vs 1); strings containing underscores ('1_0' literal syntax) or spaces.

Related errors


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