You've been recruited as a cryptographer! Your job is to build a Caesar cipher system that can encode and decode secret messages. We'll provide special conversion functions to help you work with the encrypted data.
A Caesar cipher shifts each letter by a fixed number. With a shift of 3:
a → d
, b → e
, c → f
...x → a
, y → b
, z → c
(wraps around!)def letter_to_number(letter):
return ord(letter.lower()) - 97
def number_to_letter(number):
return chr(number + 97)
Write two functions:
def encrypt(message):
# 1. Convert message to number list
# 2. Shift each letter's number by 3
# 3. Handle wrap-around (z → c)
# 4. Convert back to string
def decrypt(message):
# Do the reverse!
(value + 3) % 26
" "
secret = encrypt("meet at dawn")
print(secret) # Should print: "phhw dw gdzq"
print(decrypt(secret)) # Should print: "meet at dawn"
Your functions should now accept a secret key - the number of positions to shift. This key would be shared between the two parties sending messages.
def encrypt(message, key):
# Shift by 'key' positions instead of 3
def decrypt(message, key):
# Shift back by 'key' positions
# Example:
secret = encrypt("meet at dawn", 5)
print(secret) # Should print: "rjjy fy ifbs"
print(decrypt(secret, 5)) # Should print: "meet at dawn"
Now the key is a word! Each letter in the key determines how much to shift the corresponding letter in the message.
How it works:
a=0, b=1, c=2... z=25
def encrypt(message, key_word):
# Each letter shifts by different amount
def decrypt(message, key_word):
# Reverse the process
# Example:
secret = encrypt("meetatdawn", "cat")
# 'm' shifts by 2 (c), 'e' by 0 (a), 'e' by 19 (t),
# 't' by 2 (c), 'a' by 0 (a), 't' by 19 (t)...
print(secret) # Should print: "oetkttftwg"
print(decrypt(secret, "cat")) # Should print: "meetatdawn"
def letter_to_number(letter):
return ord(letter.lower()) - 97
def number_to_letter(number):
return chr(number + 97)