How to use default method parameters in Python

1 min

In Python, you can make default method parameters by assigning a value to the parameter when it's defined in the function signature. For example, the following function has a default parameter x with a value of 0:

def my_function(x=0):
    return x

When the function is called without any arguments, the value of x is set to 0. If you pass a value to the function, that value will be used instead:

>>> my_function()
0
>>> my_function(5)
5

You can also assign default parameters to multiple parameters in the function signature as

def my_function(x=0, y=1, z=2):
    return x, y, z

When the function is called without any arguments, the value of x, y and z will be set to 0, 1, 2 respectively. If you pass values to the function, the respective values will be used instead:

>>> my_function()
(0, 1, 2)
>>> my_function(5,6,7)
(5, 6, 7)

It's worth noting that default parameters must be placed at the end of the parameter list. If you have a non-default parameter followed by a default parameter, you will get a SyntaxError.