TheAlgorithms/Python · error · ValueError

Empty string was passed to the function

Error message

Empty string was passed to the function

What it means

bin_to_octal raises this ValueError when the input string is empty. The check is intentionally ordered after the non-binary scan (which empty strings vacuously pass), so blank input reaches this dedicated guard. It prevents the padding while-loop and 3-bit grouping from silently returning '0' for missing data.

Source

Thrown at conversions/binary_to_octal.py:25

>>> 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


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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Filter empties before the call: [bin_to_octal(t) for t in tokens if t]
  2. Substitute a default: bin_to_octal(s or '0')
  3. Validate upstream form/CLI input with a required-field check

Example fix

# before
for token in '101,,11'.split(','):
    bin_to_octal(token)
# ValueError: Empty string was passed to the function

# after
for token in '101,,11'.split(','):
    if token:
        bin_to_octal(token)
Defensive patterns

Strategy: validation

Validate before calling

tokens = [t for t in raw.split(',') if t.strip()]
[bin_to_octal(t) for t in tokens]

Type guard

def is_nonempty_str(v) -> bool:
    return isinstance(v, str) and v != ''

Try / catch

try:
    bin_to_octal(s)
except ValueError as e:
    if 'Empty string' in str(e):
        return '0'
    raise

Prevention

When it happens

Trigger: bin_to_octal(''), bin_to_octal('') from a split() empty token, bin_to_octal(None) would instead raise TypeError inside all(), so only genuinely empty strings land here.

Common situations: Blank user input; empty elements from splitting on consecutive delimiters; pipeline stages that legitimately produce empty strings and are not filtered.

Related errors


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