Default Parameters in Python

This tutorial will teach you how to use Python’s default parameters to make function calls easier.

You can give a default value for each argument when you define a function.

The following syntax is used to specify default values for parameters:

def function_name(param1, param2=value2, param3=value3, ...):

The assignment operator (=) is used to specify default values (value2, value3,…) for each parameter in this syntax.

When you call a function and send an argument to a parameter with a default value, that argument is used instead of the default value.

If the parameter is not given, the function will use the default value.

To use default parameters, you must position them after other options with default values. Otherwise, a syntax error will occur.

You can’t do something like this, for example:

def function_name(param1=value1, param2, param3):

The result causes syntax error.

default parameters in python example

The greet() method, which returns a greeting message, is defined as follows:

def greet(name, message='Hi'):
    return f"{message} {name}"

The name and message parameters are passed to the greet() function. The message argument is set to ‘Hi’ by default.

The following code invokes the greet() function with the following two arguments:

def greet(name, message='Hi'):
    return f"{message} {name}"


greeting = greet('John', 'Hello')
print(greeting)

Output

Hello John

The greet() function utilises the second parameter instead of the default value because we gave it as the second argument.

The greet() function is called without the second argument in the following example:

def greet(name, message='Hi'):
    return f"{message} {name}"


greeting = greet('John')
print(greeting)

Output

Hi John

In this situation, the greet() function utilises the message parameter’s default value.

Multiple default parameters in Python

In this case, the greet() method uses the default value for the message parameter.

def greet(name='there', message='Hi'):
    return f"{message} {name}"

You can use the greet() function without any parameters in this example:

def greet(name='there', message='Hi'):
    return f"{message} {name}"


greeting = greet()
print(greeting)

Output

Hi there

Assume you want welcome() to return a greeting like Hello there. You may create a function call like this:

def greet(name='there', message='Hi'):
    return f"{message} {name}"


greeting = greet('Hello')
print(greeting)

Unfortunately, it gives the following result:

Hi Hello

Because the greet() function interprets the ‘Hello’ argument as the first argument rather than the second.

To fix this, use keyword parameters like this when calling the greet() function:

def greet(name='there', message='Hi'):
    return f"{message} {name}"


greeting = greet(message='Hello')
print(greeting)

Output

Hello there