Page 30 - Python Tutorial
P. 30

Python Tutorial, Release 3.7.0

       expression), and methodname is the name of a method that is defined by the object’s type. Different
       types define different methods. Methods of different types may have the same name without causing
       ambiguity. (It is possible to define your own object types and methods, using classes, see Classes) The
       method append() shown in the example is defined for list objects; it adds a new element at the end of
       the list. In this example it is equivalent to result = result + [a], but more efficient.

4.7 More on Defining Functions

It is also possible to define functions with a variable number of arguments. There are three forms, which
can be combined.

4.7.1 Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that
can be called with fewer arguments than it is defined to allow. For example:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
      while True:
            ok = input(prompt)
            if ok in ('y', 'ye', 'yes'):
                   return True
            if ok in ('n', 'no', 'nop', 'nope'):
                   return False
            retries = retries - 1
            if retries < 0:
                   raise ValueError('invalid user response')
            print(reminder)

This function can be called in several ways:
   • giving only the mandatory argument: ask_ok('Do you really want to quit?')
   • giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
   • or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or
       no!')

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that

i=5

def f(arg=i):
      print(arg)

i=6
f()

will print 5.
Important warning: The default value is evaluated only once. This makes a difference when the default is
a mutable object such as a list, dictionary, or instances of most classes. For example, the following function
accumulates the arguments passed to it on subsequent calls:

24 Chapter 4. More Control Flow Tools
   25   26   27   28   29   30   31   32   33   34   35