The functions you have seen before mostly had positional arguments. When calling functions, we substitute the values according to the position of the argument names in the function definition.
If you call a function with the arguments (10, 20)
, where:
- The argument
x
will get10
- The argument
y
will get20
There is a code example:
def add(x, y):
return x + y
Variable numbers of arguments
Using positional arguments looks simple. It is as close as you can get to using functions in mathematics, and it is convenient until you need to implement them to take any number of arguments.
As you will recall, the print
function can take as many arguments as you want to pass to it. It does work if you call it without arguments at all.
So how do we teach our function to take many arguments? We need some special syntax:
def f(*args):
print(type(args))
print(args)
f()