Introduction

Argument Default value allow us to make function arguments optional.

If not passed a value, the argument is assigned its default before the function runs.

For example, here is a function that requires one argument and defaults two:

def f(a, b=2, c=3): print(a, b, c)          # a required, b and c optional 

When we call this function, we must provide a value for a, either by position or by keyword.

Providing values for b and c is optional.

If we don't pass values to b and c, they default to 2 and 3, respectively:

Demo

def f(a, b=2, c=3): print(a, b, c)          # a required, b and c optional 
#   w  w  w.j  a va 2  s.c o m
print( f(1) )       # Use defaults 
print( f(a=1) )

Result

If we pass two values, only c gets its default, and with three values, no defaults are used:

Demo

def f(a, b=2, c=3): print(a, b, c)          # a required, b and c optional 
print( f(1, 4) )    # Override defaults 
print( f(1, 4, 5) )

Result

You can use both the keyword and default features.

Demo

def f(a, b=2, c=3): print(a, b, c)          # a required, b and c optional 
# from ww w.  j  a  v a2 s .c  o  m
print( f(1, c=6) )              # Choose defaults

Result

Here, a gets 1 by position, c gets 6 by keyword, and b, in between, defaults to 2.

Related Topic