Hacking Secret Ciphers with Python

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

The code in the encryptMessage() function does the actual encryption. The key and
message text in between the parentheses next to encryptMessage()’s def statement
shows that the encryptMessage() function takes two parameters.


Parameters are the variables that contain the arguments passed when a function is called.
Parameters are automatically deleted when the function returns. (This is just like how variables
are forgotten when a program exits.)


When the encryptMessage() function gets called from line 10, two argument values are
passed (on line 10, they are the values in myKey and myMessage). These values get assigned to
the parameters key and message (which you can see on line 21) when the execution moves to
the top of the function.


A parameter is a variable name in between the parentheses in the def statement. An
argument is a value that is passed in between the parentheses for a function call.


Python will raise an error message if you try to call a function with too many or too few
arguments for the number of parameters the function has. Try typing the following into the
interactive shell:





len('hello', 'world')
Traceback (most recent call last):
File "", line 1, in
TypeError: len() takes exactly one argument (2 given)
len()
Traceback (most recent call last):
File "", line 1, in
TypeError: len() takes exactly one argument (0 given)





Changes to Parameters Only Exist Inside the Function


Look at the following program, which defines and then calls a function named func():


def func(param):
param = 42
spam = 'Hello'
func(spam)
print(spam)


When you run this program, the print() call on the last line will print out 'Hello', not 42.
When func() is called with spam as the argument, the spam variable is not being sent into the

Free download pdf