TheAlgorithms/Python · error · ValueError

key is empty

Error message

key is empty

What it means

Raised by autokey encrypt() when the key is a str but empty (''). The autokey cipher extends the key with the plaintext itself (key += plaintext), and an empty starting key would make the first len(key)==0 characters unencryptable, so it is rejected.

Source

Thrown at ciphers/autokey.py:46

    ValueError: plaintext is empty
    >>> encrypt("coffee is good as python", "")
    Traceback (most recent call last):
        ...
    ValueError: key is empty
    >>> encrypt(527.26, "TheAlgorithms")
    Traceback (most recent call last):
        ...
    TypeError: plaintext must be a string
    """
    if not isinstance(plaintext, str):
        raise TypeError("plaintext must be a string")
    if not isinstance(key, str):
        raise TypeError("key must be a string")

    if not plaintext:
        raise ValueError("plaintext is empty")
    if not key:
        raise ValueError("key is empty")

    key += plaintext
    plaintext = plaintext.lower()
    key = key.lower()
    plaintext_iterator = 0
    key_iterator = 0
    ciphertext = ""
    while plaintext_iterator < len(plaintext):
        if (
            ord(plaintext[plaintext_iterator]) < 97
            or ord(plaintext[plaintext_iterator]) > 122
        ):
            ciphertext += plaintext[plaintext_iterator]
            plaintext_iterator += 1
        elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122:
            key_iterator += 1
        else:
            ciphertext += chr(

View on GitHub (pinned to f5988cc097)

Solutions

  1. Provide a non-empty keyword: encrypt(text, 'TheAlgorithms').
  2. Default missing keys to a real value or raise your own config error before calling encrypt.
  3. Sanitize config: key = key.strip(); if not key: raise ValueError('missing key').

Example fix

# before
encrypt('hello', '')  # ValueError: key is empty

# after
encrypt('hello', 'coffee')
Defensive patterns

Strategy: validation

Validate before calling

if not key:
    raise ValueError('encryption key is missing/blank')

Type guard

def is_nonempty_str(v: object) -> bool:
    return isinstance(v, str) and len(v) > 0

Prevention

When it happens

Trigger: Calling encrypt('coffee is good as python', '') — the key argument is an empty string while plaintext is non-empty.

Common situations: Optional key parameters defaulting to '' or None-then-'' normalization, or config files with a blank key entry.

Related errors


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