Hacking Secret Ciphers with Python

(Ann) #1
Chapter 8 – The Transposition Cipher, Encrypting 115

The first step to making this list is to create as many blank strings in the ciphertext list as
there are columns. Since the number of columns is equal to the key, we can use list replication to
multiply a list with one blank string value in it by the value in key. This is how line 23 evaluates
to a list with the correct number of blank strings.


transpositionEncrypt.py



  1. Loop through each column in ciphertext.



  2. for col in range(key):

  3. pointer = col


The next step is to add text to each string in ciphertext. The for loop on line 26 will iterate
once for each column, and the col variable will have the correct integer value to use for the
index to ciphertext. The col variable will be set to 0 for the first iteration through the for
loop, then 1 on the second iteration, then 2 and so on. This way the expression
ciphertext[col] will be the string for the colth column of the grid.


Meanwhile, the pointer variable will be used as the index for the string value in the message
variable. On each iteration through the loop, pointer will start at the same value as col (which
is what line 27 does.)


Augmented Assignment Operators


Often when you are assigning a new value to a variable, you want it to be based off of the
variable’s current value. To do this you use the variable as the part of the expression that is
evaluated and assigned to the variable, like this example in the interactive shell:





spam = 40
spam = spam + 2
print(spam)
42





But you can instead use the += augmented assignment operator as a shortcut. Try typing the
following into the interactive shell:





spam = 40
spam += 2
print(spam)
42
spam = 'Hello'
spam += ' world!'
print(spam)




Free download pdf