PythonMastery
Python programs · Strings · intermediate

Caesar cipher program in Python

Shift every letter of a message a fixed number of places along the alphabet. The same function decrypts the message with a negative shift.

A Caesar cipher replaces each letter with the letter a fixed number of places further along the alphabet. With a shift of 3, A becomes D, B becomes E, and at the end of the alphabet X, Y and Z go back to A, B and C.

The program

python
def caesar(text, shift):
    result = ""
    for ch in text:
        if "a" <= ch <= "z":
            start = ord("a")
        elif "A" <= ch <= "Z":
            start = ord("A")
        else:
            result += ch  # spaces, digits and punctuation stay the same
            continue
        position = ord(ch) - start
        result += chr(start + (position + shift) % 26)
    return result


message = input("Message: ")
shift = int(input("Shift: "))

secret = caesar(message, shift)
print("Encrypted:", secret)
print("Decrypted:", caesar(secret, -shift))

Typed in this example: Meet me at the Zoo at noon!, 3. Press Run to type your own.

output
Message: Meet me at the Zoo at noon!
Shift: 3
Encrypted: Phhw ph dw wkh Crr dw qrrq!
Decrypted: Meet me at the Zoo at noon!

How it works

The program checks for the 26 English letters only. ch.isalpha() would also be True for letters such as "é", which are not in the a to z range and would be changed into the wrong characters.

Try changing it

A shift of 13 is called ROT13. Because 13 + 13 = 26, using the same shift twice gives back the original text:

python
def caesar(text, shift):
    result = ""
    for ch in text:
        if "a" <= ch <= "z":
            start = ord("a")
        elif "A" <= ch <= "Z":
            start = ord("A")
        else:
            result += ch
            continue
        result += chr(start + (ord(ch) - start + shift) % 26)
    return result


once = caesar("Hello, Grace", 13)
print(once)
print(caesar(once, 13))
output
Uryyb, Tenpr
Hello, Grace

A Caesar cipher is easy to break, because there are only 25 useful shifts to try. Use it to learn about characters and %, not to protect real data.

Learn the idea: Working with Strings, Functions & Scoping, Operators & Expressions