Hacking Secret Ciphers with Python

(Ann) #1

104 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


func() function and having 42 assigned to it. Instead, the value inside spam is being copied
and assigned to param. Any changes made to param inside the function will not change the
value in the spam variable.


(There is an exception to this rule when you are passing something called a list or dictionary
value, but this will be explained in chapter 10 in the “List References” section.)


This is an important idea to understand. The argument value that is “passed” in a function call is
copied to the parameter. So if the parameter is changed, the variable that provided the argument
value is not changed.


Variables in the Global and Local Scope


You might wonder why we even have the key and message parameters to begin with, since we
already have the variables myKey and myMessage from the main() function. The reason is
because myKey and myMessage are in the main() function’s local scope and can’t be used
outside of the main() function.


Every time a function is called, a local scope is created. Variables created during a function call
exist in this local scope. Parameters always exist in a local scope. When the function returns, the
local scope is destroyed and the local variables are forgotten. A variable in the local scope is still
a separate variable from a global scope variable even if the two variables have the same name.


Variables created outside of every function exist in the global scope. When the program exits,
the global scope is destroyed and all the variables in the program are forgotten. (All the variables
in the reverse cipher and Caesar cipher programs were global.)


The global Statement


If you want a variable that is assigned inside a function to be a global variable instead of a local
variable, put a global statement with the variable’s name as the first line after the def
statement.


Here are the rules for whether a variable is a global variable (that is, a variable that exists in the
global scope) or local variable (that is, a variable that exists in a function call’s local scope):



  1. Variables outside of all functions are always global variables.

  2. If a variable in a function is never used in an assignment statement, it is a global variable.

  3. If a variable in a function is not used in a global statement and but is used in an
    assignment statement, it is a local variable.

  4. If a variable in a function is used in a global statement, it is a global variable when
    used in that function.

Free download pdf