Search code examples
pythonencryptioncaesar-cipher

Caesar cipher encrypt. Some issues with not properly shifting the characters


Hey so i'm trying to encrypt a string, with a shift key. It works perfectly, the only issue i have is with shifting the characters. For example hello, world!0 and the shift will be 5. I want it to return as olssv, dvysk!0 Basically, only the alphabets will get encrypted. The puncutations & numbers, etc won't be shifted.

keymax = 26
def text():
    print('What message(s) are you trying to encrypt?')
    return input()

def shift():
    key = 0;
    while True:
        print('Enter the key number (1-%s)' % (keymax))
        key = int(input())
        if (key >= 1 and key <= keymax):
            return key

def encrypt(string, shift):
    hidden = ''
    for char in string:
        if char == ' ':
            hidden = hidden + char
        elif  char.isupper():
            hidden = hidden + chr((ord(char) + shift - 65) % 26 + 65)
        else:
          hidden = hidden + chr((ord(char) + shift - 97) % 26 + 97)

    return hidden

text = text()
s = shift()
print("original string: ", text)
print("after encryption: ", encrypt(text, s))

I am fairly new to python, sorry for my bad understandings. Any help would gladly be appreciated!


Solution

  • You could replace the first if statement in your encrypt function with if char.isalpha() == False:. So when the character is not an alphabetical character, the charcter doesn't get changed.

    Edit: Also to suggest an improvement, if you want to you can even have shifts upwards of 26. If you use key = key % 26 (%, called modulo, is the remainder of the division, in this case key divided by 26). This allows you to have keys that are more than 26. This doesn't really change much at all, I just personally like it more