TheAlgorithms/Python · error · ValueError

Non-hexadecimal value was passed to the function

Error message

Non-hexadecimal value was passed to the function

What it means

Raised by hex_to_decimal(hex_string) in conversions/hexadecimal_to_decimal.py:39 when, after lowercasing, stripping, and removing a leading '-', any remaining character is not in the hex_table (0-9, a-f). This is a strict per-character check, so even one bad character ('12m', '0x1f' because 'x' is not a hex digit) fails the whole conversion with ValueError('Non-hexadecimal value was passed to the function').

Source

Thrown at conversions/hexadecimal_to_decimal.py:39

        ...
    ValueError: Non-hexadecimal value was passed to the function
    >>> hex_to_decimal("")
    Traceback (most recent call last):
        ...
    ValueError: Empty string was passed to the function
    >>> hex_to_decimal("12m")
    Traceback (most recent call last):
        ...
    ValueError: Non-hexadecimal value was passed to the function
    """
    hex_string = hex_string.strip().lower()
    if not hex_string:
        raise ValueError("Empty string was passed to the function")
    is_negative = hex_string[0] == "-"
    if is_negative:
        hex_string = hex_string[1:]
    if not all(char in hex_table for char in hex_string):
        raise ValueError("Non-hexadecimal value was passed to the function")
    decimal_number = 0
    for char in hex_string:
        decimal_number = 16 * decimal_number + hex_table[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 prefix before calling: s = s.lower().removeprefix('0x') and remove separators (spaces, colons, dashes)
  2. Pre-validate: re.fullmatch(r'-?[0-9a-fA-F]+', s)
  3. If input may be any-base, use int(s, 16) inside your own try/except ValueError and map to a user-facing message

Example fix

# before
hex_to_decimal('0x1f')  # ValueError

# after
hex_to_decimal('0x1f'.removeprefix('0x'))  # 31
Defensive patterns

Strategy: validation

Validate before calling

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

Try / catch

try:
    hex_to_decimal(hex_string)
except ValueError as e:
    if 'Non-hexadecimal' in str(e):
        hex_string = hex_string.lower().removeprefix('0x').replace(' ', '')
        result = hex_to_decimal(hex_string)
    else:
        raise

Prevention

When it happens

Trigger: hex_to_decimal('12m'), hex_to_decimal('0x1f') ('x' rejected — the function does not accept the 0x prefix), hex_to_decimal('ff ff'), or hex strings with signs anywhere but position 0.

Common situations: Forgetting to strip a '0x'/'0X' prefix from formatter output; hex dumps containing spaces, colons, or newlines; mixed-case is fine (input is lowercased) but prefixes and separators are not.

Related errors


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