Python Function Default Values

Functions can have parameters with default values. For certain functions, the default value is the most common value for a parameter and is only changed for a specific reason. This makes the code calling the function more readable and removes having to provide the "usual" value as a parameter. Another advantage is that if you change the default value, it affects all the code that uses the default.  

Example

Python
def areaOfCircle(r, pi=3.14):
    return pi * r ** 2;

print("Area of a circle with radius 100 = ", areaOfCircle(100))

Output

Area of a circle with radius 100 = 31400.0

Let's say we want a more accurate value for pi:

Python
def areaOfCircle(r, pi=3.14159265359):
    return pi * r ** 2;

print("Area of a circle with radius 100 = ", areaOfCircle(100))

Output

Area of a circle with radius 100 = 31415.926535900002

Notes

Parameters with default values must always come last after any non-default parameters.

Example

Python
def defaultValuesMustBeAtTheEnd(a = 5, b):
    return a + b;

Output

def defaultValuesMustBeAtTheEnd(a = 5, b):
                               ^
SyntaxError: non-default argument follows default argument