Caesar cipher is an encryption techniques, which involves substituting each letter of the
The shift defines how many positions each letter in the alphabet would move and determines what the encrypted text would look like.
This is what encryption using Caesar cipher would look like:
In the illustration above, we have shifted the entire alphabet by
We can similarly use any number of shift ranging between
Let's implement it in Python, as follows:
def encryption(plaintext, shift):result = ""for i in range(len(plaintext)):letter = plaintext[i]if (letter == " "):result = result + " "elif (letter.isupper()):result = result + chr((ord(letter) + shift - 65) % 26 + 65)else:result = result + chr((ord(letter) + shift - 97) % 26 + 97)return resultif __name__ == "__main__":plaintext = "Hello World"shift = 10encryptedtext = encryption(plaintext, shift)print("Plain text: ", plaintext)print("Encryption text: ", encryptedtext)
Lines 1–14: We define the function encrypted()
, which takes two parameters the plaintext
and the shift
, and returns the encrypted text accordingly.
Lines 2 and 14: We define result
, which will hold the encrypted text, and return it from the function.
Line 4–12: We use a for
loop to loop over the plaintext
and encrypt it letter by letter:
Lines 7–8: We check whether the letter is a space and add a space to the encrypted text accordingly.
Lines 9–10: We check whether the letter is an uppercase letter and encrypt it accordingly to an uppercase letter.
Lines 11–12: We encrypt the letter to a lowercase letter.
Lines 16–23: We define the main
function, which calls the function encryption
to encrypt the provided text and prints encrypted text.
Free Resources