top of page

The Caesar Cipher

  • Writer: 라임 샹큼
    라임 샹큼
  • Feb 26
  • 5 min read

Have you ever wished to communicate with your friend with an alphabet only the two of you were aware of? The caesar cipher is a way of encrypting your messages by moving all the letter of the alphabet by a predetermined amount. For example if I had the letter 'a' and shifted it by 2, it would be 'c' and so on.


Coding process

This code required several processes.

A function needed to be defined and the user would need to be asked whether they wanted to encode a message or decode a message. They would then be asked what message they were targeting and by how much they wished to shift the alphabet.

This seems pretty straightforward until you consider all the implications. If I were to type in 'z' and move it by 1 then I wouldn't be able to use the index as it would be out of range.

This is where the modulo comes in. The modulo uses '%' to find the remainder of an equation. So if I had 35 as the index of a shifted letter and there are 26 letter in the alphabet(0~25 in terms of index) and did so:

35 % 26

Then it would give me 9. That would be the amount shifted. But even if the index were not out of range like so:

4 % 26

It would be 4 and the shift would have been by 4.

For the encoding process I neglected the modulo and used addition to replicate the functions like so:


def encrypt(original_text, shift_amount):

    cipher_text = ''

    for letter in original_text:

        shifted_position = alphabet.index(letter) + shift_amount

        shifted_position = shifted_position - 26

        cipher_text += alphabet[shifted_position]

    print(f'the encoded text is {cipher_text}')

encrypt(text, shift)


Here if I had the example of 'c' and shifted it by 2, shifted_position would be 2+2=4. The next line of code indicates that shifted_position would equal -22 which would be far from the required result.

In this area I mistakenly only used one example. I inserted 'z' and imagined I shifted it by 1. shifted_position would be 25+1=26, and later shifted_postion would equal to 1 which would result in 'a'.

To fix this code, I would need the modulo.


def encrypt(original_text, shift_amount):

    cipher_text = ''

    for letter in original_text:

        shifted_position = alphabet.index(letter) + shift_amount

        shifted_position %=len(alphabet)

        cipher_text += alphabet[shifted_position]

    print(f'the encoded text is {cipher_text}')

encrypt(text, shift)


This eradicates the issue.


After doing the same thing with the decrypting process, I put the two functions together and made sure to add other cases for when spaces or other letter were typed in. That would look something like this:


def caesar(original_text, shift_amount, encode_or_decode):

    if encode_or_decode == 'encode':

        cipher_text = ''

        for letter in original_text:

            if letter in alphabet:

                shifted_position = alphabet.index(letter) + shift_amount  # sp = 1

                shifted_position %=len(alphabet)

                cipher_text += alphabet[shifted_position]

            else:

                cipher_text += letter

        print(f'the encoded text is {cipher_text}')

    elif encode_or_decode == 'decode':

        decipher_text = ''

        for letter in original_text:

            if letter in alphabet:


                shifted_position1 = alphabet.index(letter) - shift_amount  # sp = -1

                shifted_position1 %= len(alphabet)

                decipher_text += alphabet[shifted_position1]

            else:

                decipher_text += letter

        print(f'the encoded text is {decipher_text}')


Here, I added a way for the code to keep on going. Adding a while function would be adequate. However, adding a while function to the newly defined function was wrong. Instead, the while function would be needed when the new caesar function was defined and implemented later on in the code.

The thing to be careful about regarding while loops is that whatever variables you put inside the loop will be cleared once the loop reloops.

So if I wanted to enter a new input to encrypt after the first round, I'd need to put my inputs into the while loop.


def caesar(original_text, shift_amount, encode_or_decode):

    if encode_or_decode == 'encode':

        cipher_text = ''

        for letter in original_text:

            if letter in alphabet:

                shifted_position = alphabet.index(letter) + shift_amount  # sp = 1

                shifted_position = shifted_position - 26

                cipher_text += alphabet[shifted_position]

            else:

                cipher_text += letter

        print(f'the encoded text is {cipher_text}')

    elif encode_or_decode == 'decode':

        decipher_text = ''

        for letter in original_text:

            if letter in alphabet:


                shifted_position1 = alphabet.index(letter) - shift_amount  # sp = -1

                shifted_position1 %= len(alphabet)

                decipher_text += alphabet[shifted_position1]

            else:

                decipher_text += letter

        print(f'the encoded text is {decipher_text}')

    restart = input('restart yes or no:\n')


restart = 'yes'

while restart == 'yes':

    direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()

    text = input("Type your message:\n").lower()

    shift = int(input("Type the shift number:\n"))

    caesar(original_text=text, shift_amount=shift, encode_or_decode=direction)


Other

When making it so that a new function can have several variable inputs, it's possible to mistake the order of the variables which can mess up the code. To prevent this, there is 'keyword arguments'. This makes it so it doesn't matter where the input is.



def greet(name, location):

    print(f'Hello {name}')

    print(f'{location} is a great place to live\n')


#keyword arguments

#usually if change the order that you put the arguments in, it will print as such

#but if add a=.., b=_, c=_ then it doesn't matter if you change the order


greet('jack', 'New jersey')

greet('New jersey', 'jack')

greet(name='jack', location='new jersey')

greet(location= 'new jersey', name= 'jack')


Hello jack

New jersey is a great place to live


Hello New jersey

jack is a great place to live


Hello jack

new jersey is a great place to live


Hello jack

new jersey is a great place to live

 
 
 

Recent Posts

See All
Stock market price alerter

Lately I’ve been getting API data from existing data and using it to get actual live data. This is done by importing requests.  This was...

 
 
 
Making a better quiz ui

I reencountered classes again. I remember I had a a hard time learning how classes were different from simply defining functions. It was...

 
 
 
Getting quotes and displaying them

from tkinter import * import requests def get_quote():     quote_url = requests.get(url=' https://api.kanye.rest ')     quote_json =...

 
 
 

1 Comment


COP
COP
May 10

Calculate Your Age Instantly with Our Smart Age Calculator! 🧮

Ever wondered exactly how old you are — not just in years, but in months, days, hours, or even seconds? Our Age Calculator is the easiest and most accurate way to find out!

Whether you're planning a birthday party, tracking milestones, or just having fun with friends, our tool delivers precise results in real time. It's more than just a number — it's your life's timeline!

🔍 Why Use Our Online Age Calculator?

Instant & Accurate: Just input your date of birth, and get a detailed breakdown of your age in years, months, days, hours, minutes, and seconds — updated live.✅ No Hassle, No Sign-Up: Use it right away without creating…

Like

© 2024 by GifTED. Powered and secured by Wix

bottom of page