Default parameter values

The formal function arguments specified when a function is defined with the def keyword are a comma-separated list of the argument names. These arguments can be made optional by providing default values. Consider a function which prints a simple banner to the console:

>>> def banner(message, border='-'):
... line = border * len(message)
... print(line)
... print(message)
... print(line)
...

This function takes two arguments, and we provide a default value — in this case '-' — in a literal string. When we define functions using default arguments, the parameters with default arguments must come after those without defaults, otherwise we will get a SyntaxError.

On line 2 of the function we multiply our border string by the length of the message string. This line shows two interesting features. First, it demonstrates how we can determine the number of items in a Python collection using the built-in len()  function. Secondly, it shows how multiplying a string (in this case the single character string border) by an integer results in a new string containing the original string repeated a number of times. We use that feature here to make a string equal in length to our message.

On lines 3 through 5 we print the full-width border, the message, and the border again.

When we call our banner() function, we don't need to supply the border string because we've provided a default value:

>>> banner("Norwegian Blue")
--------------
Norwegian Blue
--------------

However, if we do provide the optional argument, it is used:

>>> banner("Sun, Moon and Stars", "*")
*******************
Sun, Moon and Stars
*******************
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset