Better Programming

Advice for programmers.

Follow publication

Member-only story

5 Advanced Python Function Concepts Explained With Examples

Yong Cui
Better Programming
Published in
6 min readJan 14, 2021
Man using machinery
Photo by Aurelien Romain on Unsplash.

If your program is a factory, functions are its workers that maneuver the machinery to make your program run. In a typical factory, there are different types of workers tasked with varied jobs. Correspondingly, your program should be versatile in terms of its functions. To write robust functions, your coding arsenal should include the necessary tools to allow you to equip your program with the best workers.

In this article, I’d like to explain five advanced concepts related to functions in Python. Before we start the discussion, let’s assume that we understand the basic form of Python functions as annotated in the code snippet below:

1. Undetermined Arguments (*args and **kwargs)

When we define functions, we can have both positional and keyword arguments. Positional arguments are parsed by their positions, whereas keyword arguments are parsed by their argument names (i.e. the keywords or identifiers). Let’s look at the signature of the built-in print function:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The objects argument is positional (we’ll talk about the asterisk shortly). All other arguments have their unique identifiers (e.g. sep, end), and they’re thus keyword arguments. As a side note, we can have different orders when passing keyword arguments because they’re parsed by their identifiers. However, positional arguments are strictly parsed by the position. Some examples are shown below:

One thing that you may have noticed is that I passed two strings for the objects argument. That’s possible just because there is an asterisk…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

No responses yet

Write a response