Hacking Secret Ciphers with Python

(Ann) #1
Chapter 5 – The Reverse Cipher 57

Distribution license can be seen at http://invpy.com/bsd)) I like to have this info in the file so if it
gets copied around the Internet, a person who downloads it will always know where to look for
the original source. They’ll also know this program is open source software and free to distribute
to others.


reverseCipher.py


  1. message = 'Three can keep a secret, if two of them are dead.'


Line 4 stores the string we want to encrypt in a variable named message. Whenever we want to
encrypt or decrypt a new string we will just type the string directly into the code on line 4. (The
programs in this book don’t call input(), instead the user will type in the message into the
source code. You can just change the source directly before running the program again to encrypt
different strings.)


reverseCipher.py


  1. translated = ''


The translated variable is where our program will store the reversed string. At the start of the
program, it will contain the blank string. (Remember that the blank string is two single quote
characters, not one double quote character.)


The len() Function


reverseCipher.py


  1. i = len(message) - 1


Line 6 is just a blank line, and Python will simply skip it. The next line of code is on line 7. This
code is just an assignment statement that stores a value in a variable named i. The expression that
is evaluated and stored in the variable is len(message) - 1.


The first part of this expression is len(message). This is a function call to the len()
function. The len() function accepts a string value argument (just like the print() function
does) and returns an integer value of how many characters are in the string (that is, the length of
the string). In this case, we pass the message variable to len(), so len(message) will tell
us how many characters are in the string value stored in message.


Let’s experiment in the interactive shell with the len() function. Type the following into the
interactive shell:





len('Hello')
5




Free download pdf