Caesar Cipher Encryption

Learn how to BUILD the popular caesar cipher with python

Caesar cipher was originally named after Julius Caesar, who used it in his private correspondence, Caesar used a certain technique which is similar to what you are going to learn in this tutorial to convey an encoded message to his generals in the field, he deliberately did this in case the message got intercepted and got in to his opponents hands, they won’t be able comprehend them.

The principle behind the original caesar cipher is to shift the encoded message 3 letters forward from the original letter, which is what any person that doesn’t know the decode number will see, you will be able to know the actual message when you have the decode number. Well..no need to explain any further since we’ll be coding something more advanced than that and equally fun.

However, I bet you have heard someone said the word “Cryptography” or perhaps as a programmer you have come across the popular caesar cipher encryption, be it in a challenge or in programming discussion. If any of the aforementioned happens to be true, but you are not yet familiar with the concept, then pay attention to this simple caesar cipher tutorial, as it’s important for every python programmer.

ANY REQUIRED PRIOR KNOWLEDGE?

The difficulty rate for this particular caesar cipher tutorial is medium but what’s required is not that much, once you already know the basics of python like lists, string, for loop, while loop, try and except, and a few other concepts, then this should be a walk in the park..


WHAT YOU WILL LEARN IN THIS TUTORIAL

  • How to use the string library.
  • Cryptography
  • How to get information from user and assign them to variables
  • Using of while and for loops
  • How to eliminate and control possible errors from user’s end instead of showing the usual error code.

NOW LET’S CODE..

#let's import string
import string

# Let's create a list of alphabets which we'll use for encryption
alphabets = list((string.ascii_lowercase + string.ascii_uppercase)*2)

#let's create the main function that will run this program
def ceaser_cypher():

    #let's get user's intention, whether they want to encrypt or decrypt
    code_route = input('Do you want to encrypt or decrypt?, type in "encrypt" to encrypt or type in "decrypt" to decrypt\n').lower()

    #let's creat a list of keywords we expect from users
    code_route_response = ['decrypt', 'encrypt']

    
    #let's force the user to put only the information we need
    while code_route not in code_route_response:
        code_route = input('Please enter the right keyword❗, type in "encrypt" to encrypt or type in "decrypt" to decrypt\n')
    
    
#     let's get the user shift key which will use in encrypting and decrypting
#     and also capture and eliminate possible errors when the user tries putting anything else but integer
    while True:
        try:
            shift_num = int(input('Please type in your encrypt/decrypt shift key number, it must be digits:\n'))
        except:
            print('Please make sure you only typed in an integer for your encrypt/decrypt shift number:\n')
            continue
        else:
            print('Great that is an integer\n')
            break
            
            
    #let's mod the user preferred shift number by half the alphabets total number to avoid running out of range when the users uses a high shift number    
    shift_num %= 52  
    shift_num += 3
    
    #let's put a code that will convert the shift number to a negative shift number so that we can run decryption when user chooses decryption
    if code_route == 'decrypt':
        shift_num = shift_num *-1

    #let's get user's text which is to be encrypted or decrypted
    user_text = input('Please type in or paste the text you want to encrypt or decrypt:\n')

    # let's create an empty string where we will add all the encrypted/decrypted characters
    end_result = ''


    #let's make the encryption/decryption
    for char in user_text:
        if char in alphabets:
            position = alphabets.index(char)
            end_position = position + shift_num
            end_result += alphabets[end_position]
        else:
            end_result += char

    #print out the encrypted/decrypted texts accordingly
    print(f'\nYour {code_route}ed texts are as follows⤵:\n{end_result}')
    
    
# run the function    
ceaser_cypher()


#let's create a list of keywords we expect from users in other for them to run or quit the program
rerun_response = ['yes', 'no']


#let's make automate the running and quitting
rerun = True
while rerun:
    cypher_rerun = input('\nHey! would you like to use this program again🙃? type "yes" to continue or "no" to discontinue\n').lower()

    while cypher_rerun not in rerun_response:
        cypher_rerun = input('\nPlease use the right keyword to use this program again😐, type "yes" to continue or "no" to discontinue\n').lower()
    if cypher_rerun == 'yes':
        ceaser_cypher()
    else:
        print('Thank you for using Ceaser Cypher Encryption program by Geof..Bye now🤩.\n')
        rerun = False



#hope you had fun😍

SO EXPECTED OUTPUT WILL BE SOMETHING LIKE THE RESULT BELOW:

Meanwhile this output was focused on both when a user types in something other than what is expected and the user types in the expected input.

Do you want to encrypt or decrypt?, type in "encrypt" to encrypt or type in "decrypt" to decrypt
encr
Please enter the right keyword❗, type in "encrypt" to encrypt or type in "decrypt" to decrypt
encrypt
Please type in your encrypt/decrypt shift key number, it must be digits:
three
Please make sure you only typed in an integer for your encrypt/decrypt shift number:

Please type in your encrypt/decrypt shift key number, it must be digits:
200
Great that is an integer

Please type in or paste the text you want to encrypt or decrypt:
Python Engineer | Content Specialist |Virtual Assistant| "I believe that Consistently learning new things is a necessary positive attitude"

Your encrypted texts are as follows⤵:
HqlZgf wfYafWWj | ugflWfl KhWUaSdakl |NajlmSd skkaklSfl| "A TWdaWnW lZSl ugfkaklWfldq dWSjfafY fWo lZafYk ak S fWUWkkSjq hgkalanW SllalmVW"

Hey! would you like to use this program again🙃? type "yes" to continue or "no" to discontinue
yes pls

Please use the right keyword to use this program again😐, type "yes" to continue or "no" to discontinue
yes
Do you want to encrypt or decrypt?, type in "encrypt" to encrypt or type in "decrypt" to decrypt
decrypt
Please type in your encrypt/decrypt shift key number, it must be digits:
200
Great that is an integer

Please type in or paste the text you want to encrypt or decrypt:
Your encrypted texts are as follows⤵: HqlZgf wfYafWWj | ugflWfl KhWUaSdakl |NajlmSd skkaklSfl| "A TWdaWnW lZSl ugfkaklWfldq dWSjfafY fWo lZafYk ak S fWUWkkSjq hgkalanW SllalmVW"

Your decrypted texts are as follows⤵:
gwCz mvkzGxBml BmFBA izm iA nwttwEA⤵: Python Engineer | Content Specialist |Virtual Assistant| "I believe that Consistently learning new things is a necessary positive attitude"

Hey! would you like to use this program again🙃? type "yes" to continue or "no" to discontinue
Your encrypted texts are as follows⤵: HqlZgf wfYafWWj | ugflWfl KhWUaSdakl |NajlmSd skkaklSfl| "A TWdaWnW lZSl ugfkaklWfldq dWSjfafY fWo lZafYk ak S fWUWkkSjq hgkalanW SllalmVW"

Please use the right keyword to use this program again😐, type "yes" to continue or "no" to discontinue
no
Thank you for using Ceaser Cypher Encryption program by Geof..Bye now🤩.

CODE EXPLAINED..

A wise programmer once said “If you have to explain all parts of the code then your code is not that readable”, that being said, I will not explain the code line after line but I’ll choose a few spots where a beginner might have some little puzzles.

All the codes have clear comments that will solve any puzzle a total beginner might have, however at line 24, I had to use while True above the try and except to keep controlling the error which might come up and keep forcing the user to get it right.

At line 36 I had to mod the user preferred shift number(encryption/decryption number) with the half of the alphabets total number which is 52, and add 3 to it again. I did this to avoid the error of index out of range, adding 3 to it also ensures that when 52 is used as shift key we don’t end up having 0 as shift number.

In case you still don’t understand, try improving your knowledge on list and indexing in python.

At line 41 I had to use the code “shift_num = shift_num *-1” to turn the user number to negative when the user selects decrypt, as long as the user gets the number right the decryption will work just fine.

If you happen to run into any puzzle don’t hesitate to write me, or leave a comment at comment section.

To run and see this code in action click here. In case you are also on replit, you can also fork the code and play around with it.

We might actually have subsequent caesar cipher tutorial in future which might have a higher difficulty level, so remember to stay tuned by signing up to our newsletter.

🤞 Don’t miss the tips!

We don’t spam! Read more in our privacy policy

Geoff

Geoff is a python software engineer, web content specialist, tech private trainer and an IT virtual assistant.

Leave a Reply