TheAlgorithms/Python · error · ValueError

Invalid value was passed to the function

Error message

Invalid value was passed to the function

What it means

Raised by hex_to_bin(hex_num) in conversions/hex_to_bin.py:43 when int(hex_num, 16) fails after sign stripping — i.e. the remaining string is not a valid hexadecimal literal. Characters outside 0-9/a-f/A-F (including a second '-', dots, spaces, '0x' is accepted but 'g' is not) trigger this ValueError with the message 'Invalid value was passed to the function'.

Source

Thrown at conversions/hex_to_bin.py:43

    ValueError: Invalid value was passed to the function
    >>> hex_to_bin("")
    Traceback (most recent call last):
        ...
    ValueError: No value was passed to the function
    """

    hex_num = hex_num.strip()
    if not hex_num:
        raise ValueError("No value was passed to the function")

    is_negative = hex_num[0] == "-"
    if is_negative:
        hex_num = hex_num[1:]

    try:
        int_num = int(hex_num, 16)
    except ValueError:
        raise ValueError("Invalid value was passed to the function")

    bin_str = ""
    while int_num > 0:
        bin_str = str(int_num % 2) + bin_str
        int_num >>= 1

    return int(("-" + bin_str) if is_negative else bin_str)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Sanitize the string first: s = s.strip().lstrip('-').replace(' ', '') (and apply your sign handling) so only [0-9a-fA-F] remains
  2. Validate with a regex before calling: re.fullmatch(r'-?[0-9a-fA-F]+', s)
  3. Give the user a clear message by catching ValueError and re-raising with the offending input included

Example fix

# before
hex_to_bin('de ad beef')  # ValueError

# after
clean = 'de ad beef'.replace(' ', '')
print(hex_to_bin(clean))
Defensive patterns

Strategy: validation

Validate before calling

import re
if not re.fullmatch(r'-?[0-9a-fA-F]+', hex_num.strip()):
    raise ValueError(f'{hex_num!r} is not a hexadecimal string')

Try / catch

try:
    hex_to_bin(hex_num)
except ValueError:
    cleaned = re.sub(r'[^0-9a-fA-F]', '', hex_num)
    print(hex_to_bin(cleaned))

Prevention

When it happens

Trigger: hex_to_bin('F-f'), hex_to_bin('hello'), hex_to_bin('12.3'), or strings containing separators/whitespace in the middle such as 'FF FF' or 'de ad beef'.

Common situations: Passing spaced hex dumps or colon-separated MAC-style strings directly; locale/encoding artifacts embedded in the string; missing cleanup of a leading '0x' variant or sign in the wrong position.

Related errors


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