Thursday, 23 December 2021

Caesar Cipher Python - Program To Encode Text Based On The Concept of Caesar Cipher

Ceaser Cipher is an ancient concept of encoding a message. We will need two parameters here. One is for the text and the next one is for shift(the number of alphabets we are going to shift from the below alphabet list).

For example, if the text is hello and shift is 2, the output will be jgnnq

Caesar Cipher - Python Code

The alphabet variable will contain all the English alphabets. If you take a look below, we have added all the English alphabets two times. It is just done to manage when we are shifting the characters using a large number and avoid ending of the loop.

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


#The variables text and shift are used to get input from the user

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

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


#We have to create a function called encrypt in which we will encode the passed text

def encrypt(word,shift):

#//newstr is an empty string that will store the encoded character

  newstr="" 

#Below we loop through the characters in the string and encode it based on the shift value.

  for r in word:

    getindex = alphabet.index(r) + int(shift)

    newstr += alphabet[getindex]

  print(f"Actual text is: {text}")

  print(f"Actual text is: {newstr}")


#The below code is the key place where we will call the above function

encrypt(text,shift)


Output:



No comments:

Post a Comment