Every project / Techy
🔐 Secret Codes
Encrypt messages with a Caesar cipher, then crack codes without the key, like a real codebreaker.
- Language
- Python
- Level
- Beginner
- Category
- Techy
What you'll learn
- Strings & characters
- The % (modulo) operator
- Functions
- Brute-force search
- Scoring with sets
How it works
- shift() moves each letter along the alphabet, using % 26 to wrap from Z back around to A.
- Decrypting is the same shift, backwards.
- crack() tries all 26 shifts and scores each one by how many common English words it contains. The best score wins.
- Anything that isn't a letter (spaces, numbers, punctuation) stays exactly the same.
Knobs to turn
These settings are near the top of the code. Remix it, change one, and watch what happens. The preview updates as you type (press ▶ Run for Python).
| Setting | Starts at | File | What it does |
|---|---|---|---|
ALPHABET | "abcdefghijklmnopqrstuvwxyz" | cipher.py | the letters the cipher shifts |
Files
| File | Lines | |
|---|---|---|
main.py | 42 | where the program starts |
cipher.py | 37 | imported by main.py |
Challenges
Each one is a bit harder than the last. Teachers: these make good assignment instructions.
- Encrypt a message for a friend and see if they can crack it.
- Add ROT13, which is just a Caesar shift of 13.
- Make the cipher work on numbers too.
- Build a Vigenère cipher, where the shift changes with each letter of a keyword.
- Improve the cracker by scoring letter frequencies (E is the most common letter in English).