Advertisement
JkSoftware

Day 8 - Caesar Cipher.1

Nov 12th, 2021
1,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. 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']
  2.  
  3. direction = input("Type 'encode' to encrypt, type 'decode' to decrypt: ").lower()
  4. text = input("Type your message: ").lower()
  5. shift = int(input("Type the shift number:"))
  6.  
  7. #TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
  8.     #TODO-2: Inside the 'encrypt' function, shift each letter of the 'text' forwards in the alphabet by the shift amount and print the encrypted text.  
  9.     #e.g.
  10.     #plain_text = "hello"
  11.     #shift = 5
  12.     #cipher_text = "mjqqt"
  13.     #print output: "The encoded text is mjqqt"
  14.     ##HINT: How do you get the index of an item in a list:
  15.     #https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list
  16.     #TODO-3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message.
  17. #TODO-1: Create a different function called 'decrypt' that takes the 'text' and 'shift' as inputs.
  18.   #TODO-2: Inside the 'decrypt' function, shift each letter of the 'text' *backwards* in the alphabet by the shift amount and print the decrypted text.  
  19.   #e.g.
  20.   #cipher_text = "mjqqt"
  21.   #shift = 5
  22.   #plain_text = "hello"
  23.   #print output: "The decoded text is hello"
  24. #TODO-3: Check if the user wanted to encrypt or decrypt the message by checking the 'direction' variable. Then call the correct function based on that 'drection' variable.
  25. # You should be able to test the code to encrypt *AND* decrypt a message.
  26.  
  27. def encrypt(text_, shift_):
  28.     cipher_text = ""
  29.     for letter in text_:
  30.         position = alphabet.index(letter)  
  31.         new_position = position + shift
  32.         cipher_text += alphabet[new_position]
  33.     print(f"The encoded text is: \n{cipher_text}")
  34.  
  35. def decrypt(text_, shift_):
  36.     cipher_text = ""
  37.     for letter in text_:
  38.         position = alphabet.index(letter)
  39.         new_position = position - shift_
  40.         cipher_text += alphabet[new_position]
  41.     print(cipher_text)
  42.  
  43. if direction == "encode":
  44.     encrypt(text, shift)
  45. if direction == "decode":
  46.     decrypt(text, shift)
  47.  
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement