Page 140 -
P. 140

functions


          When you call a function, the computer

           creates a fresh list of variables


           But when you call a function, Python starts to record any
           new variables created in the function’s code on a new sheet
           of paper on the stack:
                                                                                   New stack frame




                                                                                         LOCAL variables used
                                                                                         by the function










           def set_password():
               password="C8H10N4O2"





           This new sheet of paper on the stack is
           called a new stack frame. Stack frames
           record all of the new variables that are
           created within a function. These are known
           as local variables.                                                      The calling code's
                                                                                     variables are still
           The variables that were created before the                                here.
           function was called are still there if the function
           needs them; they are on the previous stack frame.
           But why does the computer record variables like this?
           Your program creates a new stack frame each time it calls a function,
           allowing the function to have its own separate set of variables. If   When a variable's
           the function creates a new variable for some internal calculation, it   value can be seen by
           does so on its own stack frame without affecting the already existing
                                                                               some code, it is said
           variables in the rest of the program.
           This mechanism helps keep things organized, but                     to be “in scope.”
           it has a side-effect that is causing problems...


                                                                                       you are here 4    105
   135   136   137   138   139   140   141   142   143   144   145