Caesar Cipher in Python and How do you handle Spaces/Symbols/Numbers?

Caesar Cipher program in Python

Caesar cipher is the simple and oldest method in cryptography used by Caesar to encrypt his confidential message and sent across.

Its a shift technique, Alphabet will be shifted to another alphabet based on the shift number (secret number)

Check here to skip it to answer directly

Caesar Cipher Logic :

Message : Hello

Shift number : 1

Encryption based on the shift number:

h -> 1 -> i
e -> 1 -> f
l -> 1 -> m
l -> 1 -> m
o -> 1 -> p

Encrypted message: ifmmp

Similarly, the message will be decrypted in the reception with the shift number (secret number)

i -> 1 -> h
f -> 1 -> e
m -> 1 -> l
m -> 1 -> l
p -> 1 -> o

Decrypted message : hello

Working Code with a bug:

Bug: When the user enters any Space/Symbol/numbers as input the below code will fail (Try the below code and check for yourself)

NOTE: There is another bug in the same code (Discussed in the end of this blog)

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', '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']

direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

def caesar(text, shift, direction):
  end_text = ""
  if direction == "decode":
      shift_amount *= -1
  for letter in text:
    position = alphabet.index(letter)
    new_position = position + shift
    end_text += alphabet[new_position]
  print "Here's the " + direction + "d result: " + end_text

caesar(text, shift, direction)

Try for Yourself

Output:

Type 'encode' to encrypt, type 'decode' to decrypt:
encode
Type your message:
hello
Type the shift number:
2
Here's the encoded result: jgnnq
Type 'encode' to encrypt, type 'decode' to decrypt:
encode
Type your message:
hello 2022
Type the shift number:
5
Traceback (most recent call last):
  File "main.py", line 21, in <module>
    caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
  File "main.py", line 14, in caesar
    position = alphabet.index(letter)
ValueError: ' ' is not in list

To handle Space/Symbol/numbers in Caesar cipher

Caesar cipher Code and explanation below

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', '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']

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:

# Piece of code to handle Space/Symbol/numbers
    if char in alphabet:
      position = alphabet.index(char)
      new_position = position + shift_amount
      end_text += alphabet[new_position]
    else:
      end_text += char
  print(f"Here's the {cipher_direction}d result: {end_text}")

should_end = False
while not should_end:

  direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
  text = input("Type your message:\n").lower()
  shift = int(input("Type the shift number:\n"))

  shift = shift % 26

  caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

  restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
  if restart == "no":
    should_end = True
    print("Goodbye")

Try it Yourself

Output:

Type 'encode' to encrypt, type 'decode' to decrypt:
encode
Type your message:
hello 2022
Type the shift number:
5
Here's the encoded result: mjqqt 2022

Explanation:

  • We are checking if the input characters are available in the variable “alphabet
  • If not, then just append the character directly to the final output
  • The above code, Is skips the Space/Symbol/numbers and adds them directly to the final output

Added, We have also handled, If the user entered a shift number greater than 26

  • We added a code to modulo the input shift number to 26 and used the remainder as the actual input

For example:

Userinput = 24
24% 26 => 24
Userinput = 98
98%26 => 20

Either way, it will work as expected 🙂

Check here to code Hangman Game in Python and check here for more Python learning series posts

Good luck with your Learning

Similar Posts