Confident ยท ages 11+ ยท strings ยท ord and chr ยท functions
Secret code: the Caesar cipher in Python.
Send secret messages by shifting every letter along the alphabet.
The program
Press Run to see what it prints. Change anything you like, then run it again.
def shift(text, key):
result = ""
for ch in text:
if ch.isalpha():
base = ord("a") if ch.islower() else ord("A")
result = result + chr((ord(ch) - base + key) % 26 + base)
else:
result = result + ch
return result
secret = shift("Meet me at noon!", 3)
print(secret)
print(shift(secret, -3))Phhw ph dw qrrq! Meet me at noon!
How it works
- Julius Caesar is said to have used this code, moving each letter three places. A becomes D, B becomes E and so on.
ordturns a letter into its number andchrturns a number back into a letter.% 26wraps round from Z to A.- To decode, shift the other way:
shift(secret, -3).
Try this
- Try a different key.
- Encrypt your name.
- Try every key from 1 to 25 on a secret message and look for the one that makes sense.
Stuck on an error? Read how to debug Python.
Similar ideas
More programs
Hello world and variables
Print a message, store things in variables and join them together.
Beginner ยท ages 8+Temperature converter
Turn Celsius into Fahrenheit and print a conversion table.
Beginner ยท ages 9+Palindrome checker
Check whether a word reads the same forwards and backwards.
Easy ยท ages 10+FAQ
Secret code: the Caesar cipher: questions
What does the secret code: the caesar cipher program do?
Send secret messages by shifting every letter along the alphabet. It prints: Phhw ph dw qrrq! / Meet me at noon!
Which Python ideas does it use?
strings, ord and chr, functions. Confident level, suitable from about age 11.
How do I run it?
Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.
What should I try next?
Try a different key. Encrypt your name. Try every key from 1 to 25 on a secret message and look for the one that makes sense.
Start a conversation
Want a teacher to guide the learning?
Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.
- Tell us the learnerโs age or grade and goals
- Weโll suggest a suitable class or learning path
- Weโll confirm format, timing and fees with a parent or guardian
Play it, don't just read it
Write some code right now
Free games that need no sign-up. Pick one and play for five minutes.
Pick a game
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay