Register to get access to free programming courses with interactive exercises

Optional function parameters Python Basics

Autoservice

In programming, many functions and methods have parameters that rarely change. In such cases, we work with these parameters and give them default values that we can rewrite later. It reduces the amount of code that looks the same. Let's look at what it looks like in practice.

Let's look at an example:

# It is an exponentiation function
# The second parameter has a default value of two
def pow(x, base=2):
    return x ** base

# We calculate three to the power of two
# Two is the default setting
pow(3)  # 3 * 3 = 9
# We calculate three to the power of three
pow(3, 3)  # 3 * 3 * 3 = 27

The default value looks like a regular assignment within the definition. It's only triggered if we do not pass the parameter.

Suppose you forgot to take parts for your car to the repair shop. In this case, the repairman will offer to use default parts — ones he already has in stock.

There can even be a default value when there is only one parameter:

def my_print(text='nothing'):
  print(text)

my_print()  # => "nothing"
my_print("Hexlet")  # => "Hexlet"

There can be any number of parameters with default values:

def f(a=5, b=10, c=100):

The default values have one restriction. They must be at the very end of the parameter list. From a syntax standpoint, it's impossible to create a function with an optional parameter followed by a mandatory one:

# This code will end with an error
def f(a=5, b=10, c=100, x):
# And so will this one
def f(a=5, b=10, x, c=100):

# This code will work
def f(x, a=5, b=10, c=100):

# This code will also work
def f(x, y, a=5, b=10, c=100):

Now you know how to work with default values. They can be in several parameters or just one. And remember that the default values should be at the very end of the parameter list. It will help prevent lots of identical code from piling up.

The variable number of parameters

Some functions are different since they take a variable number of parameters. And we're not talking about default values. Check out this example:

max(1, 10, 3)  # 10

In the above example, the max() function finds the maximum value among the passed parameters. You can examine the Python documentation and learn how many parameters we can pass to the function.

You will see this construction:

max(arg1, arg2, *args[, key])

It means that max() takes two or more parameters as input:

max(1, -3, 2, 3, 2)  # 3

If the function finds several parameters with the maximum value, it will return the first one.

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY