Search code examples
pythonpython-3.xencryptioncaesar-cipher

Checking for symbols and upper/lower-case for encrypting with ceasar cipher?


I tried for several hours to make a simple ceasar cipher encryption programm. It finally works. But it is only able to encrypt text without spaces and symbols. I have no idea how to implement a checking part for these things into the code. Critics for making the code cleaner and DRY are appreciated. Thx.

The Code where i tried to implement the functionality:

#Taking Input String + converting to list
message = input("Enter the message for encrypting: ")
message_list = list(message)

#Taking Input Cipher
cipher = int(input("Enter shifting value (1-26): "))

#Alphabet
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

#Defining variable
encrypted_message = []

#Shifting
for letter in message_list:
    if letter not in alphabet:
        encrypted_message.append(letter)
    else:
        #Getting Index of the letter in alphabet
        letter_position = alphabet.index(letter)
        #Getting the shifting value for the letter
        shifting_value = letter_position + cipher
        #Getting the shifted letter
        shifted_letter = alphabet[shifting_value]
        #Adding the corresponding letter to the encrypted message
        encrypted_message.append(shifted_letter)

#Output
print("Original Message: " + message)
print("Encrypted Message: " + str(encrypted_message))
print("Cipher: " + str(cipher))

What it should do: Encrypt the Message with spaces and symbols(ceasar cipher),

What it is doing: Exception has occurred: IndexError list index out of range


Solution

  • IndexError list index out of range error occurs since you forgot the modulus. Without the modulus,

    shifting_value = letter_position + cipher
    

    this line will have higher values then the array you are indexing. Remember, Ceasar cipher is

    c = p + 3 mod 26
    

    so the line must be

    shifting_value = (letter_position + cipher) % 26

    • Note 1 : cipher is not a good variable name here. It should be shiftAmount.

    • Note 2: If you want to combine the list into string, use

      str1 = ''.join(encrypted_message)