How to encrypt a plaintext message using Caesar cipher in Python

Caesar cipher is an encryption techniques, which involves substituting each letter of the plain textPlain text refers to the unencrypted text before an encryption technique is used to modify it with another letter. Each letter is replaced by another letter at a specified number of positions down the alphabet based on the shift.

The shift defines how many positions each letter in the alphabet would move and determines what the encrypted text would look like.

Example

This is what encryption using Caesar cipher would look like:

Plain vs. encrypted texts
Plain vs. encrypted texts

In the illustration above, we have shifted the entire alphabet by 11, and this will determine what our encrypted code would look like. For example, if we decide to encrypt the plain text "BED" using a shift of 11, we get "ADC." "B" is replaced by "A," "E" is replaced by "D," and "D" is replaced by "C."

We can similarly use any number of shift ranging between 002626, where 00 and 2626 would essentially mean that there is no shift, since the letters would remain at their original positions.

Implementation

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 result
if __name__ == "__main__":
plaintext = "Hello World"
shift = 10
encryptedtext = encryption(plaintext, shift)
print("Plain text: ", plaintext)
print("Encryption text: ", encryptedtext)

Explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved