You did twelve letters in four minutes. Python does a whole book in a second. Today you write encrypt(message, shift), its matching decrypt, and a cracker that tries all 25 keys.
No reading — code. Keep 1.4 (text as numbers), 3.8 (traversal), and 3.12 (procedures with parameters) open. You finish and test this program in the 7.9 lab.
Security, in code. Keeping the Create PT skills warm in the middle of a vocabulary unit, on purpose.
The only hard part is what happens after Z.
A Caesar cipher is symmetric encryption: the same key (the shift) is used to encrypt and to decrypt. Encrypt with +3; decrypt with −3. Whoever has the key can do both.
The arithmetic for one capital letter c and a shift k:
pos = ord(c) - 65 # A→0 … Z→25 new = (pos + k) % 26 # wrap past Z result = chr(new + 65) # back to a letter
pos ← position of c (A = 0)
new ← (pos + k) MOD 26
result ← letter at newThe model, in a different costume. Same shape as your cipher — traverse, shift, wrap, build a result — on digits instead of letters:
def rotate_digits(code, shift): result = "" for ch in code: d = int(ch) result = result + str((d + shift) % 10) return result print(rotate_digits("0429", 3)) # 3752
PROCEDURE rotateDigits(digits, shift)
{
result ← []
FOR EACH d IN digits
{
APPEND(result, (d + shift) MOD 10)
}
RETURN(result)
}
DISPLAY(rotateDigits([0, 4, 2, 9], 3))Before you code the loop, make sure the math is right for a single letter. Pick a letter and a shift.
1. encrypt(message, shift) — traverse the string; shift capital letters; leave spaces and punctuation alone; return the ciphertext.
2. decrypt(message, shift) — one line, using encrypt.
3. crack(ciphertext) — print all 25 candidates, each with its shift. Read them; find the English.
ord turns a character into its number; chr turns a number back into a character. (Unit 1.4.)27 MOD 26 is 1. It’s what makes the alphabet wrap.Five questions. Trace the arithmetic on paper.