Python language basics 32: positional and keyword arguments in a function

Introduction

In the previous post we discussed how to provide optional arguments to a function. We saw how easy it was to assign a default value to a function argument using the assignment operator ‘=’. The caller could optionally ignore those arguments so that the default ones would be used within the function body. Alternatively the caller could override the defaults and provide its own argument values.

In this post we’ll look at another feature related to function arguments: positional and keyword arguments.

Positional function arguments

Consider the following function with 3 parameters:

def show_greeting(name, age, location):
    print("Welcome " + name + "! You are " + str(age) + " years old and live in " + location)

Here’s an example of calling the function:

show_greeting("Andras", 36, "Stockholm")

This is nothing special, we’ve seen functions and function calls before. This way of passing the arguments is called positional. Each argument in the function call, i.e. “Andras”, 36 and “Stockholm”, is paired up with the respective argument in the function signature: name, age, location. If we mix up the order of the arguments then we can get a funny result:

show_greeting("Stockholm", 36, "Andras")

…which prints…

Welcome Stockholm! You are 36 years old and live in Andras

Keyword arguments

You can specifically state in the function call which value belongs to which argument. In this case you can even mix up the order in which the arguments are passed:

show_greeting(location="Stockholm", age=36, name="Andras")

…which prints…

Welcome Andras! You are 36 years old and live in Stockholm

One advantage of keyword arguments is better documentation of your code. It will be easier for another programmer reviewing the code to understand which argument does what. Otherwise they may have to view the actual function code to see what the arguments mean.

If you want to mix the two strategies then the positional arguments must come first:

show_greeting("Andras", 36, location="Stockholm")

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: