TheAlgorithms/Python · error · ValueError

Height of grid can't be 0 or negative

Error message

Height of grid can't be 0 or negative

What it means

Raised by encrypt() in ciphers/rail_fence_cipher.py when the rail count (key) is <= 0. A rail fence zigzag needs at least one rail, so 0 or negative heights are rejected with a ValueError. Note key==1 or len(input) <= key short-circuits to returning the input unchanged.

Source

Thrown at ciphers/rail_fence_cipher.py:27

    >>> encrypt("Hello World", 4)
    'HWe olordll'

    >>> encrypt("This is a message", 0)
    Traceback (most recent call last):
        ...
    ValueError: Height of grid can't be 0 or negative

    >>> encrypt(b"This is a byte string", 5)
    Traceback (most recent call last):
        ...
    TypeError: sequence item 0: expected str instance, int found
    """
    temp_grid: list[list[str]] = [[] for _ in range(key)]
    lowest = key - 1

    if key <= 0:
        raise ValueError("Height of grid can't be 0 or negative")
    if key == 1 or len(input_string) <= key:
        return input_string

    for position, character in enumerate(input_string):
        num = position % (lowest * 2)  # puts it in bounds
        num = min(num, lowest * 2 - num)  # creates zigzag pattern
        temp_grid[num].append(character)
    grid = ["".join(row) for row in temp_grid]
    output_string = "".join(grid)

    return output_string


def decrypt(input_string: str, key: int) -> str:
    """
    Generates a template based on the key and fills it in with
    the characters of the input string and then reading it in
    a zigzag formation.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive rail count: encrypt('message', 2) or higher
  2. Validate at the UI boundary: reject keys < 1 before calling
  3. Remember key=1 returns the plaintext unchanged (no zigzag)

Example fix

# before
encrypt('message', 0)

# after
encrypt('message', 3)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(key, int) or key < 1:
    raise ValueError('rail count must be a positive integer')

Type guard

def valid_rail_key(key) -> bool:
    return isinstance(key, int) and key >= 1

Try / catch

try:
    ciphertext = encrypt(message, key)
except ValueError as exc:
    if "Height of grid" in str(exc):
        raise ConfigError('rail fence key must be >= 1') from exc
    raise

Prevention

When it happens

Trigger: encrypt('message', 0); encrypt('message', -10); key derived from len arithmetic that underflowed to 0; passing a bool False (== 0).

Common situations: User-supplied key parsed with int() that accepted 0 or a negative number; key = rails - 2 style off-by-one math; config defaults left unset.

Related errors


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