BYU logo Computer Science

Keyword arguments in functions you write

We previously discussed keyword arguments and how they work with print. This covered calling functions that take keyword arguments.

Now we are going to show you how to write functions that take keywords arguments.

Here is a function that prints bullets at the start of each line:

def print_with_bullets(lines, bullet='*'):
    for line in lines:
        print(f'{bullet} {line}')

The first argument is a list of lines that you want to print. This is a positional argument. The second argument is the character you want to use for the bullets. This is a keyword argument because it has an = after the name of the argument, and then a default value.

If you call this function without the bullets argument:

lines = [
    'Hello.',
    'Cosmo is the best mascot.',
    'Python is pretty cool.'
]

print_with_bullets(lines)

then it will print a * in front of every line:

* Hello.
* Cosmo is the best mascot.
* Python is pretty cool.

However, if you provide the bullets argument, then you can print whatever you want at the start of each line:

print_with_bullets(lines, bullet='>')

This will print:

> Hello.
> Cosmo is the best mascot.
> Python is pretty cool.