Skip to contentSkip to navigation

Module 18 · Lesson 02

Project: Caesar Cipher

Build a Caesar cipher tool: shift letters with modular arithmetic while keeping case and punctuation, decrypt by shifting back, and break a message with an unknown shift by scoring every possibility.

  • About 10 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Position, shift, wrap, break
  • One shift, part by part
  • Build the cipher in five steps
  • Watch a word get shifted

The cipher in four parts

Letters become numbers, numbers move, then they become letters again.

  • Position

    ord(ch) - ord("a") turns a letter into a number from 0 to 25.

  • Shift and wrap

    Add the shift, then % 26 brings z back round to a.

  • Keep the rest

    Capitals stay capital. Spaces, digits and punctuation are copied as they are.

  • Break it

    Try all 26 shifts and keep the one that looks most like English.

Shift ciphers everywhere

Too weak for secrets, but still used for fun every day.

  • Spoiler hidingForums use ROT13, a shift of 13, so nobody reads an ending by accident.
  • Puzzle gamesHidden messages in games are often a simple shift.
  • Escape roomsA cipher wheel on the wall turns a clue into the code.
  • HistoryJulius Caesar is said to have used a shift of 3 in his letters.

Shifting one letter

This line is the whole cipher. Tap each part to see its job.

Part 1 of 6

Tap any part of the code below, or press Next.1 of 6 explored

back to a letter:Turns the final code point back into a character.

Build the cipher in five steps

Build the project one step at a time. Each example runs on its own: change it, then press Run.

Example 1 of 61. Letters as numbers

ord gives a letter's number. Subtract the code of a to get its place in the alphabet.

Your turn: Try capitals. What number does ord("A") give?

Python
for ch in "abz":
    print(ch, ord(ch), ord(ch) - ord("a"))
print(chr(ord("a") + 7))
Output
Press Run to see what it prints.

Watch a word get shifted

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. word = "Zo!"
  2. out = ""
  3. for ch in word:
  4. if ch.isalpha():
  5. base = 65 if ch.isupper() else 97
  6. ch = chr((ord(ch) - base + 1) % 26 + base)
  7. out += ch
  8. print(out)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.A negative remainder:

print(-1 % 26)

0 of 6 answered

Common cipher misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Building the cipher

The brief

The program encrypts a message by shifting every letter a fixed number of places along the alphabet, so with a shift of 3, a becomes d and z wraps round to c. Capital letters stay capital, and anything that is not a letter is left alone. It also decrypts, and, given only an encrypted message, it finds the most likely shift on its own.

Letters as numbers

Every character has a code point, which ord returns and chr turns back into a character. The lowercase letters are consecutive, from ord("a") == 97 to ord("z") == 122, and the capitals run from 65 to 90. Subtracting the code of a gives a letter's position in the alphabet, from 0 to 25:

Try it 1: edit me, then Run
position = ord("h") - ord("a")      # 7
print(chr(position + ord("a")))     # h
Output
Press Run to see what it prints.

Working with positions rather than raw codes is the key idea: the alphabet becomes the numbers 0 to 25, and shifting is addition.

Wrapping round with %

Adding 3 to the position of y (24) gives 27, which is past the end of the alphabet. The remainder operator brings it back: 27 % 26 is 1, which is b. Python's % always returns a result between 0 and 25 for a positive divisor, even for negative numbers, so (1 - 3) % 26 is 24. That means the same formula works for shifting forwards and backwards:

Try it 2: edit me, then Run
def shift_letter(ch, shift):
    base = ord("a") if ch.islower() else ord("A")
    return chr((ord(ch) - base + shift) % 26 + base)
Output
Press Run to see what it prints.

Keeping case and punctuation

The encrypt function looks at each character in turn. Letters are shifted using the base that matches their case; everything else, such as spaces, digits, commas and accented letters, is copied unchanged. Using ch.isascii() and ch.isalpha() as the test avoids shifting letters such as é, whose code points are far from the plain alphabet. Collect the characters in a list and join them once at the end, which is faster than adding to a string in a loop.

Decrypting is encrypting backwards

There is no need for a second function full of almost identical code. Shifting by -shift undoes a shift, so decryption is one line:

Try it 3: edit me, then Run
def decrypt(text, shift):
    return encrypt(text, -shift)
Output
Press Run to see what it prints.

This is a small example of a big idea: when two operations are inverses, write one and express the other in terms of it. Then there is only one place for a bug to hide, and the round-trip test decrypt(encrypt(m, k), k) == m checks both at once.

A faster version with translate

Python can do the per-character work in C with a translation table. str.maketrans(source, target) maps each character of source to the character in the same position of target, and text.translate(table) applies it:

Try it 4: edit me, then Run
import string

def make_table(shift):
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    k = shift % 26
    return str.maketrans(lower + upper, lower[k:] + lower[:k] + upper[k:] + upper[:k])

print("Hello, World!".translate(make_table(3)))   # Khoor, Zruog!
Output
Press Run to see what it prints.

Slicing the alphabet at k and putting the front part on the end builds the shifted alphabet in one expression. Characters not in the table pass through unchanged, so punctuation needs no special handling.

ROT13

A shift of 13 is special: since 13 + 13 = 26, applying it twice gives the original text, so the same function both encrypts and decrypts. It is still used to hide spoilers and puzzle answers, and Python even includes it as codecs.encode(text, "rot13").

Breaking the cipher

With only 26 possible shifts, an attacker does not need the key at all. They try every shift and look at the results. A person can spot the readable one at a glance, but a program needs a score. Two simple scores work well:

  • Count how many decrypted words appear in a small set of very common words such as the, and, is and of.
  • Count letters with Counter and compare against how often letters appear in normal English, where e, t and a are the most common.

max(range(26), key=score) then picks the best shift. Ties are possible on very short messages, and max returns the first best one it finds, which here is the smallest shift.

Why this is not security

Twenty-six keys can be tried by hand in minutes, and a computer tries them in microseconds. Real encryption uses keys with so many possibilities that trying them all is impossible, and it is designed by specialists. Use libraries such as cryptography for anything that matters, never a cipher you wrote yourself.

Ideas to extend it

Add a command-line menu, encrypt a whole file, or try the Vigenere cipher, which uses a different shift for each letter taken from a keyword and is much harder to break by hand.

Syntax

The general shape of the statements in this lesson.

syntax.py
ord("a"), chr(97)                         # code point and back
(ord(ch) - base + shift) % 26 + base      # shift with wrap-around
ch.isascii() and ch.isalpha()             # only plain letters move
"".join(parts)                            # build the result once
decrypt = lambda t, k: encrypt(t, -k)     # inverse operation
str.maketrans(src, dst); text.translate(t)   # fast table version
lower[k:] + lower[:k]                     # shifted alphabet
max(range(26), key=score)                 # best shift when breaking
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Encrypt, decrypt and check the round trip

Intermediate

Write encrypt with translation tables, define decrypt in terms of it, and check that decrypting gives the original message back for every possible shift, including negative and large ones.

Python
import string

LOWER, UPPER = string.ascii_lowercase, string.ascii_uppercase

def encrypt(text, shift):
    k = shift % 26
    table = str.maketrans(LOWER + UPPER, LOWER[k:] + LOWER[:k] + UPPER[k:] + UPPER[:k])
    return text.translate(table)

def decrypt(text, shift):
    return encrypt(text, -shift)

message = "Meet me at Platform 9, café at 10."
secret = encrypt(message, 3)
print(secret)
print(decrypt(secret, 3))
print(encrypt("Zebra", 27), encrypt("Zebra", -1))
print(all(decrypt(encrypt(message, k), k) == message for k in range(-30, 60)))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The table maps each plain letter to its shifted partner, so digits, punctuation and the accented é pass through untouched. shift % 26 makes a shift of 27 the same as 1 and a shift of -1 the same as 25. The final line is the round-trip test: it tries 90 different shifts and confirms decrypt always undoes encrypt.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Forgetting to wrap around

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
print(chr(ord('y') + 3))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints | instead of b: the code runs past z into punctuation

Write this instead

print(chr((ord('y') - ord('a') + 3) % 26 + ord('a')))

Why it happens

Adding to the code point never comes back to a; nothing tells it the alphabet has only 26 letters.

In the real world

Where this shows up in software people use every day.

  1. Hiding puzzle answers

    Publishing

    A puzzle website prints the answers on the same page as the clues. To stop readers seeing them by accident, the answers are stored in ROT13 and decoded only when a reader presses Reveal.

    Why Python fits

    ROT13 is built into Python's codecs module, so no table is needed. It is not meant to keep a secret from a determined reader, only to make the answer unreadable at a glance, which is exactly the job here. The round-trip line confirms that decoding restores every answer.

    Python
    import codecs
    
    answers = {"1 across": "LIGHTHOUSE", "2 down": "Orchid", "3 across": "jazz"}
    
    hidden = {clue: codecs.encode(word, "rot13") for clue, word in answers.items()}
    for clue, word in hidden.items():
        print(f"{clue:<9} {word}")
    
    print("Reveal 2 down:", codecs.decode(hidden["2 down"], "rot13"))
    print("Round trip ok:", all(codecs.decode(w, "rot13") == answers[c] for c, w in hidden.items()))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why does Python's % work for negative shifts?

In Python the result of % has the same sign as the divisor, so (n % 26) is always 0 to 25. In some other languages a negative number gives a negative remainder, which is why shift ciphers there need an extra + 26.

Can I encrypt accented letters or other alphabets?

Not with this formula: it only knows the 26 plain letters. Leaving other characters unchanged is the safe choice. A cipher for another alphabet would need its own list of letters and its own modulus.

Is the translate version always better?

It is faster and shorter, which matters for long texts. The loop version is easier to follow and to step through in a debugger, so it is a good first version to write and test against.

What should I use to really protect data?

A well-reviewed library such as cryptography, with keys stored safely. Homemade ciphers, however clever, are almost always breakable.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.