A Caesar cipher replaces each letter with the letter a fixed number of places further along the alphabet. With a shift of 3, A becomes D, B becomes E, and at the end of the alphabet X, Y and Z go back to A, B and C.
The program
def caesar(text, shift): result = "" for ch in text: if "a" <= ch <= "z": start = ord("a") elif "A" <= ch <= "Z": start = ord("A") else: result += ch # spaces, digits and punctuation stay the same continue position = ord(ch) - start result += chr(start + (position + shift) % 26) return result message = input("Message: ") shift = int(input("Shift: ")) secret = caesar(message, shift) print("Encrypted:", secret) print("Decrypted:", caesar(secret, -shift))
Typed in this example: Meet me at the Zoo at noon!, 3. Press Run to type your own.
Message: Meet me at the Zoo at noon! Shift: 3 Encrypted: Phhw ph dw wkh Crr dw qrrq! Decrypted: Meet me at the Zoo at noon!
How it works
ord()gives the number for a character, andchr()turns a number back into a character.ord("a")is 97 andord("d")is 100.positionis where the letter is in the alphabet, from 0 for "a" to 25 for "z".% 26makes the alphabet go round in a circle. "Z" is position 25, plus 3 is 28, and28 % 26is 2, which is "C".- Decrypting is the same as encrypting with
-shift. In Python,%with a positive number on the right never gives a negative answer:(0 - 3) % 26is 23, so "a" goes back to "x".
The program checks for the 26 English letters only. ch.isalpha() would also be True for letters such as "é", which are not in the a to z range and would be changed into the wrong characters.
Try changing it
A shift of 13 is called ROT13. Because 13 + 13 = 26, using the same shift twice gives back the original text:
def caesar(text, shift): result = "" for ch in text: if "a" <= ch <= "z": start = ord("a") elif "A" <= ch <= "Z": start = ord("A") else: result += ch continue result += chr(start + (ord(ch) - start + shift) % 26) return result once = caesar("Hello, Grace", 13) print(once) print(caesar(once, 13))
Uryyb, Tenpr Hello, Grace
A Caesar cipher is easy to break, because there are only 25 useful shifts to try. Use it to learn about characters and %, not to protect real data.