Every project / Techy

🔐 Secret Codes

Encrypt messages with a Caesar cipher, then crack codes without the key, like a real codebreaker.

Secret Codes running
Language
Python
Level
Beginner
Category
Techy
▶ Try it & remix

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).

SettingStarts atFileWhat it does
ALPHABET"abcdefghijklmnopqrstuvwxyz"cipher.pythe letters the cipher shifts

Files

FileLines
main.py42where the program starts
cipher.py37imported by main.py

Challenges

Each one is a bit harder than the last. Teachers: these make good assignment instructions.

  1. Encrypt a message for a friend and see if they can crack it.
  2. Add ROT13, which is just a Caesar shift of 13.
  3. Make the cipher work on numbers too.
  4. Build a Vigenère cipher, where the shift changes with each letter of a keyword.
  5. Improve the cracker by scoring letter frequencies (E is the most common letter in English).