Keyword and positional arguments
When calling functions we provide values for the arguments so that the function executes using those values. It’s possible to provide those values with both positional and keyword arguments:
def rectangle(h, w, val=0): return [[val] * w] * h print(rectangle(2, 3, 1)) # [[1, 1, 1], [1, 1, 1]]
def rectangle(h, w, val=0): return [[val] * w] * h print(rectangle(2, w=3, val=1)) # [[1, 1, 1], [1, 1, 1]]
We can provide values for arguments by specifying the names of those arguments like we did in the second example (
This is especially useful for functions that have many arguments and most of them have default values. In that case, we can provide the keyword arguments for only the parameters we need and skip the rest.
Note that keyword arguments don’t need to be provided in the same order as the function argument. They can have an arbitrary order as long as their names match the arguments of the function. It’s also important to note that positional arguments cannot follow keyword arguments. When calling a function we first specify the positional arguments and only then the keyword arguments. Can you think of why that’s the case 🤔?
Given the function that prints the properties of a patient, call it 3 times with the following order of arguments:
- name, age, height
- age, name, height
- height, age, name
The outputs of each call need to be the same, but you can use both positional and keyword arguments to call the function.
Time limit: 1 seconds
Memory limit: 512 MB
Output limit: 1 MB