Skip to main content

11.8) Arguments (cont'd)


Default values: It might be appropriate to provide a default value to an input argument.

def vol_sphere(radius, pi=3.14):
    return 4./3.*pi*(radius**3)

Notice how we have added an assignment in our definition of arguments. You can now omit the argument pi when you call the function; pi is now an optional argument:

 >>> print vol_sphere(1.0)
4.18666666667

or you can specify a different value for pi:

>>> print vol_sphere(1., pi=3.14159)
4.18878666667

Lists and dictionaries as arguments: If you have a long list of arguments, writing out all of the arguments when you call a function becomes a source of potential mistakes. There’s a really nifty way of passing in the arguments as a list, if they’re positional, or as a dictionary using their keyword. You can even use both at once:

>>> args=[1.]
>>> kwds={'pi':3.14159}
>>> print vol_sphere(*args,**kwds)
4.18878666667

Of course you can also decide to input all the arguments in a list or as keywords in a dictionary.