Positional arguments

A function definition can contain more than a single parameter. The easiest way to pass multiple arguments to a function is to use positional arguments that need to be in same order the parameters were written. The first argument in the function call will become the first parameter, the second argument the second parameter and so on.

Consider the following example:

def describe_me(name, gender):
    print('My name:', name)
    print('My gender:', gender)


describe_me('Tuna', 'M')

The output:

>>>
My name: Tuna
My gender: M
>>>

In the code above we’ve defined the function describe_me() that takes two parameters – name and gender. The values of these parameters will then be printed. We’ve than called the function and passed two arguments – ‘Tuna‘ and ‘M‘. The first argument was stored in the first parameter defined in the function definition (name). The second argument was stored in the second parameter defined (gender).

Note that you need to specify both arguments when calling a function. Considers what happens if I call the function with only a single argument specified:

describe_me('Tuna')
>>>
Traceback (most recent call last):
File "functions.py", line 16, in <module>
describe_me('Tuna')
TypeError: describe_me() missing 1 required positional argument: 'surname'
>>>

Python reported an error because a required positional argument was not specified.

One of the main benefits of using functions in your code is that you can call the same function multiple times. In our example, we could define another person with a new function call:

describe_me('Tuna','M')
describe_me('Tanya','F')
describe_me('John','M')

>>>
My name: Tuna
My gender: M
My name: Tanya
My gender: F
My name: John
My gender: M
>>>

The order of the arguments in the function call matters! Consider what happens if we call our function with the gender specified first:

describe_me('M','Tuna')
>>>
My name: M
My gender: Tuna
>>>
Geek University 2022