Hacking Secret Ciphers with Python

(Ann) #1

84 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


If num is greater than or equal to 26 , then the condition on line 36 is True and line 37 is
executed (and the elif statement on line 38 is skipped). Otherwise, Python will check if num is
less than 0. If that condition is True, then line 39 is executed.


The Caesar cipher adds or subtracts 26 because that is the number of letters in the alphabet. If
English only had 25 letters, then the “wrap-around” would be done by adding or subtracting 25.


Notice that instead of using the integer value 26 directly, we use len(LETTERS). The function
call len(LETTERS) will return the integer value 26 , so this code works just as well. But the
reason that we use len(LETTERS) instead of 26 is that the code will work no matter what
characters we have in LETTERS.


We can modify the value stored in LETTERS so that we encrypt and decrypt more than just the
uppercase letters. How this is done will be explained at the end of this chapter.


caesarCipher.py



  1. add encrypted/decrypted number's symbol at the end of translated



  2. translated = translated + LETTERS[num]


Now that the integer in num has been modified, it will be the index of the encrypted (or
decrypted) letter in LETTERS. We want to add this encrypted/decrypted letter to the end of the
translated string, so line 42 uses string concatenation to add it to the end of the current value
of translated.


caesarCipher.py


  1. else:


  2. just add the symbol without encrypting/decrypting



  3. translated = translated + symbol


Line 44 has four spaces of indentation. If you look at the indentation of the lines above, you’ll see
that this means it comes after the if statement on line 26. There’s a lot of code in between this
if and else statement, but it all belongs in the block of code that follows the if statement on
line 26. If that if statement’s condition was False, then the block would have been skipped and
the program execution would enter the else statement’s block starting at line 46. (Line 45 is
skipped because it is a comment.)


This block has just one line in it. It adds the symbol string as it is to the end of translated.
This is how non-letter strings like ' ' or '.' are added to the translated string without being
encrypted or decrypted.

Free download pdf