TheAlgorithms/Python · error · ValueError

Invalid number of bands. Resistor bands must be 3 to 6

Error message

Invalid number of bands. Resistor bands must be 3 to 6

What it means

Raised by check_validity() in electronics/resistor_color_code.py when number_of_bands falls outside the supported 3-6 range (the function explicitly tests `number_of_bands >= 3 and number_of_bands <= 6`). The library models only 3-, 4-, 5-, and 6-band resistors; note calculate_resistance() re-raises this same condition.

Source

Thrown at electronics/resistor_color_code.py:292

    >>> check_validity(3, ["Cyan","Red","Yellow"])
    Traceback (most recent call last):
      ...
    ValueError: Cyan is not a valid color

    """
    if number_of_bands >= 3 and number_of_bands <= 6:
        if number_of_bands == len(colors):
            for color in colors:
                if color not in valid_colors:
                    msg = f"{color} is not a valid color"
                    raise ValueError(msg)
            return True
        else:
            msg = f"Expecting {number_of_bands} colors, provided {len(colors)} colors"
            raise ValueError(msg)
    else:
        msg = "Invalid number of bands. Resistor bands must be 3 to 6"
        raise ValueError(msg)


def calculate_resistance(number_of_bands: int, color_code_list: list) -> dict:
    """
    Function calculates the total resistance of the resistor using the color codes.
    Function takes number_of_bands, color_code_list as input and returns
    resistance

    >>> calculate_resistance(3, ["Black","Blue","Orange"])
    {'resistance': '6000Ω ±20% '}

    >>> calculate_resistance(4, ["Orange","Green","Blue","Gold"])
    {'resistance': '35000000Ω ±5% '}

    >>> calculate_resistance(5, ["Violet","Brown","Grey","Silver","Green"])
    {'resistance': '7.18Ω ±0.5% '}

    >>> calculate_resistance(6, ["Red","Green","Blue","Yellow","Orange","Grey"])

View on GitHub (pinned to f5988cc097)

Solutions

  1. Restrict number_of_bands to one of 3, 4, 5, or 6.
  2. For 2-band resistors, extend the color list with an explicit 'Black' multiplier band (and a tolerance) so it becomes a valid 3/4-band call.
  3. Validate the range upstream (e.g. in a CLI argument parser with choices=[3,4,5,6]) before calling the library.

Example fix

# before
check_validity(2, ["Red", "Red"])  # ValueError

# after
check_validity(3, ["Red", "Red", "Black"])  # 2-band code normalized to 3 bands
Defensive patterns

Strategy: validation

Validate before calling

SUPPORTED_BANDS = (3, 4, 5, 6)
if number_of_bands not in SUPPORTED_BANDS:
    raise UserInputError(f"Band count must be one of {SUPPORTED_BANDS}")

Type guard

def is_supported_band_count(n) -> bool:
    return isinstance(n, int) and 3 <= n <= 6

Try / catch

try:
    ok = check_validity(number_of_bands, colors)
except ValueError as exc:
    raise InvalidBandSpec(str(exc)) from exc

Prevention

When it happens

Trigger: check_validity(2, ['Red','Red']) or check_validity(7, [...]) — 2-band and 7-band codes are unsupported; passing 0 or a negative count; passing a count parsed from text that failed int conversion earlier.

Common situations: Handling legacy 2-band resistors (implicit multiplier) which this library does not model; off-by-one when computing band count from a list length; new band counts added after a library update.

Related errors


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