Home » Implementing the Caesar Cipher in Python

Implementing the Caesar Cipher in Python

was a Roman ruler known for his military strategies and excellent leadership. Named after him, the Caesar Cipher is a fascinating cryptographic technique that Julius Caesar employed to send secret signals and messages to his military personnel.

The Caesar Cipher is quite basic in its working. It works by shifting all the letters of the message to be encrypted by a fixed number of places, called the key. The person receiving it is aware of the key and uses it to decrypt the message, thereby providing an easy and intelligent way of conducting private correspondence.

Understanding the Project

In this article, we will learn how to implement the Caesar Cipher in Python. This is a beginner-friendly project where we will be using conditional statements, loops and functions to encode and decode user input data.

Here is how the program will work: The program asks the user for a message to be encoded or decoded. The user chooses either encryption or decryption. The program asks for the key by which the message will be encrypted. Once the user gives the key, the program will convert the message by converting each letter of the message according to the key, either by shifting the letters forward if encoding, or backward if decoding.

Let us first define the project steps with the help of a flowchart.

Step 1: Defining the Alphabet List

First of all, we will use the List datatype in Python to create a list of the letters in the alphabet. Python lists are a sequence of items in a specific order and have several built-in functions. The program will use this list as a reference to shift letters forward or backward according to the choice of encoding or decoding. Let us define the list, 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']

Step 2: Ask User Input

The next step is to take the user’s input. We will ask the user:

  1. Whether they want to encode or decode a message encode_or_decode
  2. The respective message secret_message which they want to encode or decode, and
  3. The shift number key by which the message will be encoded or decoded.
encode_or_decode = input("Type 'encode' to encrypt, type 'decode' to decrypt:n").lower()
secret_message = input("Type your message here:n").lower()
key = int(input("Type the key:n"))

Make sure to convert the key into an int datatype, otherwise you might run into a problem in shifting the letter by the number of key as Python will consider the input as a string and not an integer type. Also remember to convert the user input secret_message and encode_or_decode to lowercase to match the items in the list alphabet and conditional statment that will come ahead.

Step 3: Defining Functions and Using the Modulo Operator

The next step is to define both the encode and decode functions which will be called later. The encode function will be called when the user chooses ‘encode’ in the encode_or_decode input prompt, and the decode function will be called when the user types ‘decode’ in the encode_or_decode input prompt.

Both functions are quite straightforward to code. It will take the secret_message, loop through all the letters, and for all the letters in the alphabet list that we defined earlier, it will take their index position, add the key to it, and give the shifted_position. We will use this shifted_position as an index of the letters and add them to the output_text which will be the encoded or decoded message.

But we have one problem here! What if by shifting the letters, the index position goes out of the alphabet list? Well the solution to this is using an interesting Python operator called the ‘modulo‘. The modulo is an operator that gives the remainder after division and is symbolized by ‘%’ in Python. So 8 % 5 will equal 3, as 3 is the remainder left after 8 is divided by 5.

We will use this operator in our encode and decode functions. So, considering the alphabet list has 26 items, and if the user gives a message to encode “vampire” and key as “10”, if we just add the key number to the index position of ‘v’, 22 + 10 = 32, we will have an error as there is no item at the 32nd position in the alphabet list. However, if we want to restart the alphabet list after ‘z’ from ‘a’, the 32nd alphabet would fall on ‘f’, which is the 6th item in the alphabet list. The same letter and index position can be achieved using the modulo operator; for a shifted value of 32, the letter will be at the 32 % 26 = 6th position. So we will use the same logic in coding our encode and decode functions.

Here is the encode function:

def encode(message, keynumber, operation):
    output_text = ""
    for letter in message:
        if letter in alphabet:
            shifted_position = alphabet.index(letter) + keynumber
            shifted_position = shifted_position % len(alphabet)
            output_text = output_text + alphabet[shifted_position]
        else:
            output_text += letter       
    print("Here is the encoded text : ", output_text)

So if I want to encode “I have a pet cat” with the key number ‘6’, I will get the following encoded message:

Encoded Message (Image by Author)
Photo by Bogdan Farca on Unsplash

For the decode function, since we are decoding, we have to shift the letters by the key in the reverse order, that is, backwards. So if I want to decode the above message: ‘o ngbk g vkz igz’, I will have to multiply the key number by -1, so that instead of adding the key, it subtracts the key, and the shifted_position will be achieved by moving the index position backward.

Let us define the decode function:

def decode(message, keynumber, operation):
    keynumber = keynumber * -1
    output_text = ""
    for letter in message:
        if letter in alphabet:
            shifted_position = alphabet.index(letter) + keynumber
            shifted_position = shifted_position % len(alphabet)
            output_text = output_text + alphabet[shifted_position]
        else:
            output_text += letter       
    print("Here is the decoded text : ", output_text)

Here is our decoded message:

Decoded Message (Image by Author)

Step 4: Calling Functions

Once our functions are defined, we will call them when needed. If the user wants to encrypt a message, we will call the encode function, and if they want to decrypt a message, we will call the decode function. Let us implement this in our code using conditional statements if, elif, and else:

if encode_or_decode == 'encode':
    encode(message=secret_message, keynumber=key, operation=encode_or_decode)
elif encode_or_decode == 'decode':
    decode(message=secret_message, keynumber=key, operation=encode_or_decode)
else:
    print("Error")

Step 5: Program Continuity

The last step of this program is to ask the user whether they want to continue with the program of encryption and decryption or end. We will implement this with a variable continue_program that will be True at the beginning and will remain so when the user wants to continue with the program. If the user wants to end, the variable will change to False, and the program will end. We will include this condition in a while loop that will run as long as the variable remains True.

continue_program = True

while continue_program:

    encode_or_decode = input("Type 'encode' to encrypt, type 'decode' to decrypt:n").lower()
    secret_message = input("Type your message here:n").lower()
    key = int(input("Type the key:n"))

    if encode_or_decode == 'encode':
        encode(message=secret_message, keynumber=key, operation=encode_or_decode)
    elif encode_or_decode == 'decode':
        decode(message=secret_message, keynumber=key, operation=encode_or_decode)
    else:
        print("Error")
        
    restart = input("Type 'yes' if you want to continue with the program.nOtherwise, type 'no'.n").lower()
    if restart == "no":
        continue_program = False

Conclusion

With the inclusion of the while loop above, we have successfully implemented the Caesar cipher program in Python. This project explored conditional statements if, elif, and else, for and while loops, and defining and calling functions. Moreover, we also introduced the modulo operator in this program to handle exceptions.

You can find the complete source code of this project here.

If you have any questions or want to share a different approach, feel free to comment on this article. I will look forward to it. Happy coding! 🙂

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *