TheAlgorithms/Python · error · ValueError

Third rotor position is not within range of 1..26 ({rotorpos

Error message

Third rotor position is not within range of 1..26 ({rotorpos3}

What it means

Raised by the Enigma machine validator when the THIRD rotor position is outside 1..26. Identical rule to the other two rotor checks; this message's f-string is correctly closed.

Source

Thrown at ciphers/enigma_machine2.py:106

    :return: (`rotpos`, `rotsel`, `pb`)
    """
    # Checks if there are 3 unique rotors

    if (unique_rotsel := len(set(rotsel))) < 3:
        msg = f"Please use 3 unique rotors (not {unique_rotsel})"
        raise Exception(msg)

    # Checks if rotor positions are valid
    rotorpos1, rotorpos2, rotorpos3 = rotpos
    if not 0 < rotorpos1 <= len(abc):
        msg = f"First rotor position is not within range of 1..26 ({rotorpos1}"
        raise ValueError(msg)
    if not 0 < rotorpos2 <= len(abc):
        msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})"
        raise ValueError(msg)
    if not 0 < rotorpos3 <= len(abc):
        msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})"
        raise ValueError(msg)

    # Validates string and returns dict
    pbdict = _plugboard(pb)

    return rotpos, rotsel, pbdict


def _plugboard(pbstring: str) -> dict[str, str]:
    """
    https://en.wikipedia.org/wiki/Enigma_machine#Plugboard

    >>> _plugboard('PICTURES')
    {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}
    >>> _plugboard('POLAND')
    {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}

    In the code, ``pb`` stands for ``plugboard``

View on GitHub (pinned to f5988cc097)

Solutions

  1. Keep the third position in 1..26, e.g. rotpos=(1, 13, 26)
  2. Validate the full tuple before the call
  3. Reject out-of-range settings at the UI/config layer

Example fix

# before
rotpos = (1, 1, 99)

# after
rotpos = (1, 1, 26)
Defensive patterns

Strategy: validation

Validate before calling

assert all(0 < p <= 26 for p in rotpos), "positions must be in 1..26"

Type guard

def valid_rotor_positions(rotpos) -> bool:
    return len(rotpos) == 3 and all(0 < p <= 26 for p in rotpos)

Try / catch

try:
    settings = validate_and_transform(rotpos, rotsel, pb)
except ValueError as exc:
    if "rotor position" in str(exc):
        raise ConfigError("rotor settings out of range 1..26") from exc
    raise

Prevention

When it happens

Trigger: rotpos=(1, 1, 0), (26, 26, 27), or any third element < 1 or > 26.

Common situations: Loop-generated settings where the last rotor got a boundary value; typos in hand-written triplets; mixing 0-based indexing in generated test cases.

Related errors


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