Python language basics 30: providing default values to a function

Introduction

In the previous post we looked at how objects are passed by reference to function in Python. We saw how it could be dangerous to let a function modify an incoming parameter if you’re not aware of the reference passing behaviour. We also briefly looked at the idea of a deep copy which is one way to keep your original objects intact.

In this post we’ll diverge from objects and instead investigate a feature of functions: default arguments.

Default arguments are simply provided by the assignment operator ‘=’ in the arguments list:

def multiply(base, multiplier=2, show_greeting=True):
    if show_greeting:
        print("Welcome to the multiply function")
    return base * multiplier

The above function has one compulsory arguments and 2 optional ones. If you omit the ‘multiplier’ and ‘show_greeting’ arguments then their default values 2 and True will be used in the multiply function:

result = multiply(10)

‘result’ will be 20 and the greeting will be printed in the output window. You can override the default values by simply passing in the values for those arguments:

result = multiply(10, 3, False)

‘result’ will be 30 and the greeting won’t be shown.

Note that default arguments must be given last in the argument list. The following won’t work:

def multiply(multiplier=2, base,  show_greeting=True):

You’ll get an error saying that a non-default argument follows a default one.

In the next post we’ll look at positional and keyword arguments to a Python function.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: