Python Default Arguments

Rate this post

This tutorial introduces the concept of default arguments in Python.

A default argument is a function argument that takes on a default value if you don’t pass an explicit value for when calling the function. For example, the function definition def f(x=0): <body> allows you to call it with or without the optional argument x—valid calls are f(2), f(4), or even f(). But if you don’t pass the optional argument, it’ll just assign the default value 0 to argument x.

Examples Default Argument

def f(x=0):
    print(x)

f(10)
# 10

f(-2)
# -2

f('hello world')
# hello world

########################
# DEFAULT ARGUMENT     #
########################
f()
# 0

Application: When to Use Default Arguments?

Suppose, you have created a Python command line tool for your business. The tool requires user confirmation for different activities like writing or deleting files.

To avoid redundant code, you have implemented a generic function that handles the interaction with the user. The default behavior should consist of three steps.

  • (1) You ask (prompt) the user a question.
  • (2) The user puts in some response.
  • (3) As long as the response is invalid, the function repeats up to four times--each time printing a reminder 'Try again: yes or no?'.

The number of repetitions and the reminder should be customizable via the parameters.

To achieve this, you can specify default arguments as given in the following code snippet. You can use the default parameters by calling ask_ok('May we send you a free gift?'). Or you can overwrite them in the order of their definition (one, several, or all parameters).

def ask_ok(prompt, retries=4, reminder='Try again: yes or no?'):
    while retries>0:
        ok = input(prompt)
        if ok in ('y', 'yes'):
            return True
        if ok in ('n', 'no'):
            return False
        retries = retries - 1
        print(reminder)

ask_ok('May we send you a free gift?')

Let’s check how you understand this concept of default arguments.

Puzzle Default Arguments

Is ask_ok('Howdy?', 5) a valid function call?

It is interesting that only 50% of all finxter users solve this puzzle: they seem to guess the answer. Partial replacement of default arguments is a new feature to most of the users. Is it new to you?

Mastering these basic language features will lift you to the level of an advanced coder.

Are you a master coder?
Test your skills now!

Related Video

Python 3 Programming Tutorial - Function Parameter Defaults