Skip to content

Functions with Default Values

Functions with default values, or default arguments, are a mechanism that allows a function to receive parameters with default values if an argument is not provided when calling it. This makes it easier to write more flexible and versatile functions.

In the function definition, a value is assigned to each parameter that can have a default value.

When calling the function, the arguments corresponding to the parameters with default values can be omitted, and the function will use these values instead.

In this section, we will explore how to construct functions in Python in a flexible and reusable way. We will see different ways to define and use parameters to adapt to different needs, such as default values or optional arguments.

We can make a parameter optional, which helps to make the use of the function more flexible for different scenarios.

greet.py
def greet(name, surname=None):
if surname:
print(f'Hello, {name} {surname}')
else:
print(f'Hello, {name}')
name = 'Py'
surname = 'Docs'
greet(name)
greet(name, surname)

Output:

greet.py
Hello, Py
Hello, PyDocs

If the user does not provide the second argument (exponent), the function defaults to squaring (exponent = 2). This allows the function to be used more flexibly, without always having to write both arguments.

power.py
def power(base, exponent=2):
print(f'{base} raised to {exponent} is {base ** exponent}')
power(5) # Uses the default value 2
power(5, 3) # Uses the provided value

Output:

power.py
5 raised to 2 is 25 5 raised to 3 is 125
  • Flexibility: Allows you to call the function in different ways, depending on the need.

  • Simplification: Avoids the need to pass unnecessary arguments in all cases.

  • Increased readability: Facilitates code comprehension by explicitly showing the default values.