Caesar Cipher implemented simple in Python

What will we cover?

We will implement the Caesar Cipher in Python using functions and a few things.

For futter preparation than given in this tutorial you can watch this video tutorial.

Step 1: Describing Caesar Cipher

  • The Caesar Cipher is a simple substitution cipher, which is limited to only shift the characters by fixed number.
  • Let’s take an example
    • Imagine you got the message: BRX DUH DZHVRPH. What to make out of it. Makes no sense.
    • But what if we get help from this diagram

Step 2: Implement the encryption function

Let’s implement a helper function encrypt_char(char, key) to encrypt a single character, char, with key.

def encrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + key) % 26)

Then we can implement encrypt_message(message, key), which uses the helper function.

def encrypt_message(message, key):
    message = message.upper()
    cipher = ''
    for char in message:
        if char not in ' ,.':
            cipher += encrypt_char(char, key)
            cipher += char
    return cipher

Let’s try it.

encrypt_message("you are awesome.", 3)

Which results in BRX DUH DZHVRPH.

Step 3: Implement the decryption function

This is quite similar.

def decrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + 26 - key) % 26)

def decrypt_message(cipher, key):
    cipher = cipher.upper()
    message = ''
    for char in cipher:
        if char not in ' ,.':
            message += decrypt_char(char, key)
            message += char
    return message

Let’s try it.

decrypt_message('BRX DUH DZHVRPH.', 3)

Then you get YOU ARE AWESOME.

What next?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.

Leave a Reply