Page 99 -
P. 99

sharing your code


           Use optional arguments


           To turn a required argument to a function into an optional argument, provide
           the argument with a default value. When no argument value is provided, the
           default value is used. When an argument value is provided, it is used instead
           of the default. The key point is, of course, that the default value for the
           argument effectively makes the argument optional.
           To provide a default value for any function argument, specify the default
           value after the argument name:                                          Both arguments
                                                                                  are REQUIRED.


                                      def print_lol(the_list, level):







                                                                                       The addition of a

                                     def print_lol(the_list, level=0):                  default value has
                                                                                        turned “level” into an
                                                                                        OPTIONAL argument.



           With the default value for the argument defined, you can now invoke the
           function in a number of different ways:


             Invoke the function and
             provide both arguments.

                                     nester.print_lol(movies, 0)
                                                                                      Invoke the function with
                                                                                      one argument and use
                                     nester.print_lol(movies)                         the default value for
                                                                                      the second.
             Invoke the function with
             both arguments, but     nester.print_lol(movies, 2)
             provide an alternative
             starting value for the
             second argument.



          Your function now supports different signatures, but the
           functonality remains as it was.

                                                                                       you are here 4    63
   94   95   96   97   98   99   100   101   102   103   104