Hacking Secret Ciphers with Python

(Ann) #1

106 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


print(spam)
UnboundLocalError: local variable 'spam' referenced before assignment


When the spam variable is used on lines 1, 19, 21, 23, 25 it is outside of all functions, so this is
the global variable named spam. In the eggs() function, the spam variable is assigned the
integer 99 on line 4, so Python regards this spam variable as a local variable named spam.
Python considers this local variable to be completely different from the global variable that is also
named spam. Being assigned 99 on line 4 has no effect on the value stored in the global spam
variable since they are different variables (they just happen to have the same name).


The spam variable in the ham() function on line 8 is never used in an assignment statement in
that function, so it is the global variable spam.


The spam variable in the bacon() function is used in a global statement, so we know it is
the global variable named spam. The spam = 0 assignment statement on line 13 will change the
value of the global spam variable.


The spam variable in the CRASH() function is used in an assignment statement (and not in a
global statement) so the spam variable in that function is a local variable. However, notice that
it is used in the print() function call on line 16 before it is assigned a value on line 17. This is
why calling the CRASH() function causes our program to crash with the error,
UnboundLocalError: local variable 'spam' referenced before
assignment.


It can be confusing to have global and local variables with the same name, so even if you
remember the rules for how to tell global and local variables apart, you would be better off using
different names.


Practice Exercises, Chapter 8, Set B


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


The List Data Type


transpositionEncrypt.py



  1. Each string in ciphertext represents a column in the grid.



  2. ciphertext = [''] * key


Line 23 uses a new data type called the list data type. A list value can contain other values. Just
like how strings begin and end with quotes, a list value begins with a [ open bracket and ends

Free download pdf