13.5: Optional parameters

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    13.5: Optional parameters

    We have seen built-in functions and methods that take optional arguments. It is possible to write programmer-defined functions with optional arguments, too. For example, here is a function that prints the most common words in a histogram:

    def print_most_common(hist, num=10):
        t = most_common(hist)
        print('The most common words are:')
        for freq, word in t[:num]:
            print(word, freq, sep='\t')
    

    The first parameter is required; the second is optional. The default value of num is 10.

    If you only provide one argument:

    print_most_common(hist)
    

    num gets the default value. If you provide two arguments:

    print_most_common(hist, 20)
    

    num gets the value of the argument instead. In other words, the optional argument overrides the default value.

    If a function has both required and optional parameters, all the required parameters have to come first, followed by the optional ones.


    This page titled 13.5: Optional parameters was last modified on Tue, 01 Dec 2020 03:31:07 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.