Hacking Secret Ciphers with Python

(Ann) #1

58 http://inventwithpython.com/hacking


Email questions to the author: [email protected]





len('')
0
spam = 'Al'
len(spam)
2
len('Hello' + ' ' + 'world!')
12





From the return value of len(), we know the string 'Hello' has five characters in it and the
blank string has zero characters in it. If we store the string 'Al' in a variable and then pass the
variable to len(), the function will return 2. If we pass the expression 'Hello' + ' ' +
'world!' to the len() function, it returns 12. This is because 'Hello' + ' ' +
'world!' will evaluate to the string value 'Hello world!', which has twelve characters in
it. (The space and the exclamation point count as characters.)


Line 7 finds the number of characters in message, subtracts one, and then stores this number in
the i variable. This will be the index of the last character in the message string.


Introducing the while Loop


reverseCipher.py


  1. while i >= 0:


This is a new type of Python instruction called a while loop or while statement. A while
loop is made up of four parts:



  1. The while keyword.

  2. An expression (also called a condition) that evaluates to the Boolean values True or
    False. (Booleans are explained next in this chapter.)

  3. A : colon.

  4. A block (explained later) of indented code that comes after it, which is what lines 9 and
    10 are. (Blocks are explained later in this chapter.)

Free download pdf