Skip to content

Instantly share code, notes, and snippets.

@Jithender5913
Created December 13, 2021 12:06
Show Gist options
  • Select an option

  • Save Jithender5913/41ba896f8290adb70b6d29f69cc77ee9 to your computer and use it in GitHub Desktop.

Select an option

Save Jithender5913/41ba896f8290adb70b6d29f69cc77ee9 to your computer and use it in GitHub Desktop.
Caesar Cipher using Python
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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def encrypt(plain_text, shift_amount):
cipher_text = " "
for letter in plain_text:
position = alphabet.index(letter)
new_position = position + shift_amount
new_letter = alphabet[new_position]
cipher_text += new_letter
print(f"The encrypted code is {cipher_text}")
encrypt(plain_text=text, shift_amount=shift)
# Decrypting cipher
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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def decrypt(plain_text, shift_amount):
decipher_text = " "
for letter in plain_text:
position = alphabet.index(letter)
new_position = position - shift_amount
new_letter = alphabet[new_position]
decipher_text += new_letter
print(f"The decrypted code is {decipher_text}")
decrypt(plain_text=text, shift_amount=shift)
# Reorganising the code
def caesar(start_text, shift_amount, cipher_direction):
end_text = " "
if cipher_direction == "decode":
shift_amount *= -1
for letter in start_text:
position = alphabet.index(letter)
new_position = position + shift_amount
end_text += alphabet[new_position]
print(f"The {cipher_direction}d is {end_text}")
caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment