Caesar cipher
Hints and examples are shown, check as often as you like, no timer.
Subject
The Caesar cipher shifts every letter of a word by k positions in the alphabet; after Z we come back to A. Example with k = 3: HELLO becomes KHOOR.
Question 1
4 ptsWrite a function saisie_mot() that reads a non-empty word made only of capital letters A–Z (repeat otherwise) and returns it.
saisie_mot() ⟵ HELLO → 'HELLO'
Hint
Combine m != "", m.isalpha() and m.isupper().
Question 2
6 ptsWrite a function crypter(mot, k) that returns the word encrypted with shift k.
crypter("ABC", 1) → 'BCD'
Hint
chr((ord(c) - 65 + k) % 26 + 65) shifts one capital letter.
Question 3
4 ptsWrite a function decrypter(mot, k) that returns the original word.
decrypter("BCD", 1) → 'ABC'
Hint
Decrypting with k is encrypting with -k.
Question 4
6 ptsMain program: read the word with saisie_mot(), then k (integer 1 ≤ k ≤ 25, repeat otherwise). Display the encrypted word, then on the next line the decrypted word.
Inputs: HELLO, 3 → KHOOR ⏎ HELLO
Hint
Two print() calls: one per line.
Your program
Saved automatically in this browser.
One line per input() call, used by “Run”.
Model solution
def saisie_mot():
m = input("Donner un mot : ")
while not (m != "" and m.isalpha() and m.isupper()):
m = input("Donner un mot : ")
return m
def crypter(mot, k):
res = ""
for c in mot:
res = res + chr((ord(c) - 65 + k) % 26 + 65)
return res
def decrypter(mot, k):
return crypter(mot, -k)
# Programme principal
mot = saisie_mot()
k = int(input("Donner k : "))
while not (1 <= k <= 25):
k = int(input("Donner k : "))
c = crypter(mot, k)
print(c)
print(decrypter(c, k))
The first run downloads Python (~6 MB) and can take a few seconds.