Reputation: 13
I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. Problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters and when the letter z for example the program doesn't restart at the beginning of the alphabet PS i am french educated so some lines might be in french Here's my code:
list=list()
r=0
choix=int(input("Veuillez entrer 1 pour coder ou 2 pour decoder"))
if choix==1 :
cle=int(input("Quelle est votre clé?"))
phrase=input("Quelle est votre phrase? ")
for i in phrase :
r=ord(i)
r=(r+cle)%26
lettre=chr(r)
list.append(lettre)
print(list)
elif choix==2 :
cle=int(input("Quelle est votre clé?"))
phrase=input("Quelle est votre phrase? ")
for i in phrase :
r=ord(i)
r=(r-cle)%26
lettre=chr(r)
list.append(lettre)
print(list)
Upvotes: 1
Views: 614
Reputation: 44376
Some points:
liste_lettre
but you never do anything with it.%
. Upvotes: 0
Reputation: 428
Here is a shift cipher function that might get you started.
def shift_cipher(phrase, shift):
'''Ceaser Ciphers/Unciphers a string'''
alphabet = list(string.ascii_lowercase)
phrase = str(phrase)
phrase = phrase.lower()
new_phrase = ''
for letter in phrase:
shift_letter_index = alphabet.index(letter) + shift
new_phrase += alphabet[shift_letter_index % 26]
return new_phrase
Upvotes: 1
Reputation: 553
Ok bear with me here, I only have the first part (the encoding), but I think it is enough for you to be able to do the rest:
code=list()
choix=int(input("Veuillez entrer 1 pour coder ou 2 pour decoder"))
if choix==1 :
cle=int(input("Quelle est votre clé?"))
phrase=input("Quelle est votre phrase? ")
for el in phrase:
if el.islower():
r = ((ord(el) - ord('a')) + cle) % 26 + ord('a')
code.append(chr(r))
elif el.isupper():
r = ((ord(el) - ord('A')) + cle) % 26 + ord('A')
code.append(chr(r))
else:
code.append(el)
print(code)
The tricky part here is this: ((ord(el) - ord('a')) + cle) % 26 + ord('a')
, since you want to loop through the smaller case letters, you have to constrain your computation between ord('a')
which is 97
and ord('z')
which is 122
. As @Malvolio suggested using the modulus, does the "restarting".
Upvotes: 1