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_octal raises this ValueError when the input contains any character other than '0' or '1'. Note the check order: the non-binary scan runs first, so a string like 'a-1' or '2' hits this error, while a truly empty string passes all() (vacuously true) and is caught by the separate empty check below. No '-' sign is handled here — '-101' is rejected by this check.

Source

Thrown at conversions/binary_to_octal.py:23

'17'

>>> bin_to_octal("101010101010011")
'52523'

>>> bin_to_octal("")
Traceback (most recent call last):
    ...
ValueError: Empty string was passed to the function
>>> bin_to_octal("a-1")
Traceback (most recent call last):
    ...
ValueError: Non-binary value was passed to the function
"""


def bin_to_octal(bin_string: str) -> str:
    if not all(char in "01" for char in bin_string):
        raise ValueError("Non-binary value was passed to the function")
    if not bin_string:
        raise ValueError("Empty string was passed to the function")
    oct_string = ""
    while len(bin_string) % 3 != 0:
        bin_string = "0" + bin_string
    bin_string_in_3_list = [
        bin_string[index : index + 3]
        for index in range(len(bin_string))
        if index % 3 == 0
    ]
    for bin_group in bin_string_in_3_list:
        oct_val = 0
        for index, val in enumerate(bin_group):
            oct_val += int(2 ** (2 - index) * int(val))
        oct_string += str(oct_val)
    return oct_string

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass only raw '0'/'1' characters: strip prefixes and signs beforehand
  2. Handle negatives yourself: sign = s.startswith('-'); bin_to_octal(s.lstrip('-')) with sign reapplied
  3. For signed input, int(s, 2) then oct() is a simpler pipeline

Example fix

# before
bin_to_octal('-101')
# ValueError: Non-binary value was passed to the function

# after
s = '-101'
sign = '-' if s.startswith('-') else ''
sign + bin_to_octal(s.lstrip('-')).lstrip('0') or '0'
Defensive patterns

Strategy: type-guard

Validate before calling

import re
if not re.fullmatch(r'[01]+', bin_string):
    raise ValueError(f'expected raw binary digits: {bin_string!r}')
bin_to_octal(bin_string)

Type guard

def is_raw_binary(s) -> bool:
    return isinstance(s, str) and s != '' and all(c in '01' for c in s)

Try / catch

try:
    bin_to_octal(s)
except ValueError as e:
    if 'Non-binary' in str(e):
        s = re.sub(r'[^01]', '', s)
        return bin_to_octal(s)
    raise

Prevention

When it happens

Trigger: bin_to_octal('a-1'), bin_to_octal('2'), bin_to_octal('-101') (negative binary not supported, unlike bin_to_decimal), bin_to_octal('0b110') because of the 'b'.

Common situations: Reusing negative-binary handling from binary_to_decimal, which this function does not share; passing bin() repr with the 0b prefix; typo digits.

Related errors


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