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
% 26brings 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
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?
for ch in "abz":
print(ch, ord(ch), ord(ch) - ord("a"))
print(chr(ord("a") + 7))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.
- word = "Zo!"
- out = ""
- for ch in word:
- if ch.isalpha():
- base = 65 if ch.isupper() else 97
- ch = chr((ord(ch) - base + 1) % 26 + base)
- out += ch
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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 breakingPress 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
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.
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)))Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
print(chr(ord('y') + 3))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Publishing
Hiding puzzle answers
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.
Pythonimport 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()))OutputPress 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?
Can I encrypt accented letters or other alphabets?
Is the translate version always better?
What should I use to really protect data?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.