Hacking Secret Ciphers with Python

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

Tracing Through the Program, Step by Step


The previous explanations have gone through what each line does, but let’s go step by step
through the program the same way the Python interpreter does. The interpreter starts at the very
top, executes the first line, then moves down a line to execute the next instruction. The blank lines
and comments are skipped. The while loop will cause the program execution will loop back to
the start of the loop after it finishes.


Here is a brief explanation of each line of code in the same order that the Python interpreter
executes it. Follow along with to see how the execution moves down the lines of the program, but
sometimes jumps back to a previous line.


reverseCipher.py



  1. Reverse Cipher




  2. http://inventwithpython.com/hacking (BSD Licensed)





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

  4. translated = ''



  5. i = len(message) - 1

  6. while i >= 0:

  7. translated = translated + message[i]

  8. i = i - 1



  9. print(translated)


Step 1 Line 1 This is a comment, so the Python interpreter skips it.
Step 2 Line 2 This is a comment, and skipped.


Step 3 Line 4 (^) The string value 'Three can keep a secret, if two of
them are dead.' is stored in the message variable.
Step 4 Line 5 The blank string '' is stored in the translated variable.
Step 5 Line 7 len(message) - 1 evaluates to 48. The integer 48 is stored in the i
variable.
Step 6 Line 8 (^) The while loop’s condition i >= 0 evaluates to True. Since the
condition is True, the program execution moves inside the following
block.
Step 7 Line 9 translated + message[i] to '.'. The string value '.' is stored
in the translated variable.
Step 8 Line 10 (^) i - 1 evaluates to 47. The integer 47 is stored in the i variable.
Step 9 Line 8 When the program execution reaches the end of the block, the execution
moves back to the while statement and rechecks the condition. i >= 0

Free download pdf