Hacking Secret Ciphers with Python

(Ann) #1

120 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


value. That is why addNumbers(2, 40) evaluates to 42 , which is the value stored in spam
on line 4 and next printed to the screen on line 5.


Practice Exercises, Chapter 8, Set E


Practice exercises can be found at http://invpy.com/hackingpractice8E.


Back to the Code


transpositionEncrypt.py



  1. Convert the ciphertext list into a single string value and return it.



  2. return ''.join(ciphertext)


The encryptMessage() function’s return statement returns a string value that is created
by joining all of the strings in the ciphertext list. This final string is the result of our
encryption code.


The great thing about functions is that a programmer only has to know what the function does,
but not how the function’s code does it. A programmer can understand that if she calls the
encryptMessage() function and pass it an integer and a string for the key and message
parameters, the function call will evaluate to an encrypted string. She doesn’t need to know
anything about how the code in encryptMessage() actually does this.


The Special name Variable


transpositionEncrypt.py



  1. If transpositionEncrypt.py is run (instead of imported as a module) call




  2. the main() function.



  3. if name == 'main':

  4. main()


We can turn our transposition encryption program into a module with a special trick involving the
main() function and a variable named name.


When a Python program is run, there is a special variable with the name name (that’s two
underscores before “name” and two underscores after) that is assigned the string value
'main' (again, two underscores before and after “main”) even before the first line of your
program is run.


At the end of our script file (and, more importantly, after all of our def statements), we want to
have some code that checks if the name variable has the 'main' string assigned to
it. If so, we want to call the main() function.

Free download pdf