Home » Learn Python » Functions » Keyword and Variable Arguments

Keyword and Variable Arguments

If you place an asterisk before a parameter name, it allows you to specify multiple arguments, which will appear as a tuple.

In this code, the first parameters is a normal parameter; the second is a variable parameter.

def greeting(salutation, *people):

    for person in people:
        print(f'{salutation} {person}!')

greeting("Hi", "Bob", "Sarah", "Jim")
<class 'tuple'>
Hi Bob!
Hi Sarah!
Hi Jim!

Keyword Arguments

When you supply arguments to a function, you can name the parameters (keyword arguments) rather than matching them by their position (positional arguments).

def greeting(salutation, person):
    print(f'{salutation} {person}!')

greeting(person="Bob", salutation="Hi")
Hi Bob!

Variable Keyword Arguments

If you use a double asterisk before a parameter name, it will accept an arbitrary list of keyword arguments. This will be supplied as a dictionary.

def greeting(**people):

greeting(person="Bob", salutation="Hi")
<class 'dict'>
{'person': 'Bob', 'salutation': 'Hi'}

Default Arguments

You can supply default values for arguments. These are used if you don’t supply a value when you call the function.

def greeting(person, salutation="Hi"):
    print(f'{salutation} {person}')

greeting("Sarah", "Hello")
Hi Bob
Hello Sarah

Leave a Reply

Blog at WordPress.com.