Search code examples
pythonpython-3.xcryptographycaesar-cipherpython-3.10

Caesar cipher looping


I have some code which has other problems as well at the moment but I'm really struggling with the looping part (going from z back to a).

I've looked at a buch of other answers but found none that actually helped in my situation.

import string
upper = string.ascii_uppercase
lower = string.ascii_lowercase
digit = string.digits
letters = string.ascii_letters


delrv = input("Vill du kryptera, skriv K. Vill du dekryptera, skriv D")
inm = input("Skriv en text eller siffror")
nyckel = (input("Ange nycklar"))
lista = []
listad = []

splitNyckel = nyckel.split(" ")
splitNyckel = [int(a) for a in splitNyckel]

#kryptering
if(delrv == "K" or delrv == "k"):
    for i in range(len(inm)):
        #for a in range(len(splitNyckel)):
            #rakning = ord(inm[i]) + 1
            #if(rakning == 90):
            
            #elif(rakning == 122):

        if(ord(inm[i]) + splitNyckel[i] == 90):
            lista[i] = 65
        elif(ord(inm[i]) + splitNyckel[i] == 122):
            lista[i] = 97
        lista.append(ord(inm[i]) + splitNyckel[i])
        print(chr(lista[i]))



#Dekryptering
if(delrv == "D" or delrv == "d"):
    for i in range(len(inm)):
        lista.append(ord(inm[i]) - splitNyckel[i])
        print(chr(lista[i]))

Solution

  • There are a couple of ways you could do this.

    The most basic would be to just subtract 26 anytime you go past the range you are trying to stay within. Or in the case of shifting the other direction and ending up somewhere before a/A, you could add 26 instead.

    Another option would be to use the mod operator to stay within a certain range, e.g. (some_val - ord('a')) % 26 + ord('a') would keep you within the range of ord('a') and ord('z'). This would have an advantage over pure addition or subtraction in that it would work for shifts greater than 26 as well.