how does the ciphering part works for the following code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how does the ciphering part works for the following code?

# encrypt and decrypt a text using a simple algorithm of offsetting the letters key = 'abcdefghijklmnopqrstuvwxyz' def encrypt(n, plaintext): """Encrypt the string and return the ciphertext""" result = '' for l in plaintext.lower(): try: i = (key.index(l) + n) % 26 result += key[i] except ValueError: result += l return result.lower() def decrypt(n, ciphertext): """Decrypt the string and return the plaintext""" result = '' for l in ciphertext: try: i = (key.index(l) - n) % 26 result += key[i] except ValueError: result += l return result text = "I am coding Python on SoloLearn!" offset = 5 encrypted = encrypt(offset, text) print('Encrypted:', encrypted) decrypted = decrypt(offset, encrypted) print('Decrypted:', decrypted)

29th Aug 2016, 8:40 AM
Aditya Warade
Aditya Warade - avatar
2 Answers
+ 1
I think now I understand. First he create the list key, which contains all the letters. Then he defines the function encrypt(n,plaintext). This function takes the plaintext in lowercase (.lower) and goes all over the text, searching for the position of each letter in the list "key". Then add n (5 in example) to that index. The "%26" helps if the index + n is bigger than 26, return again to the start of the list. Finally, it create a value for result with result+=key[i], creating other list but "offseated" 5 places. If you introduce anything that is not in the list, like a number, it will make the exception and will return the same that you entered.
29th Aug 2016, 1:15 PM
Alejandro Pérez Moreno
Alejandro Pérez Moreno - avatar
0
Same question
29th Aug 2016, 12:50 PM
Alejandro Pérez Moreno
Alejandro Pérez Moreno - avatar