Hacking Secret Ciphers with Python

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

what causes translated to hold the reverse of the string in the message. When i is finally
set to - 1 , then the while loop’s condition will be False and the execution jumps to line 12.


reverseCipher.py


  1. print(translated)


At the end of our program on line 12, we print out the contents of the translated variable
(that is, the string '.daed era meht fo owt fi ,terces a peek nac eerhT') to
the screen. This will show the user what the reversed string looks like.


If you are still having trouble understanding how the code in the while loop reverses the string,
try adding this new line inside the while loop:


reverseCipher.py


  1. while i >= 0:

  2. translated = translated + message[i]

  3. print(i, message[i], translated)

  4. i = i - 1



  5. print(translated)


This will print out the three expressions i, message[i], and translated each time the
execution goes through the loop (that is, on each iteration of the loop). The commas tell the
print() function that we are printing three separate things, so the function will add a space in
between them. Now when you run the program, you can see how the translated variable
“grows”. The output will look like this:


48..
47 d .d
46 a .da
45 e .dae
44 d .daed
43 .daed
42 e .daed e
41 r .daed er
40 a .daed era
39 .daed era
38 m .daed era m
37 e .daed era me
36 h .daed era meh
35 t .daed era meht
34 .daed era meht
33 f .daed era meht f
32 o .daed era meht fo
31 .daed era meht fo

Free download pdf