In this example, a
and b
are said to be positional arguments. They must appear in exactly the order they are the defined and they cannot be omitted.
def sum(a, b):
return a + b
Calling our function with a=1
and b=2
returns the expected answer 3
.
sum(1,2)
Likewise with a=2
and b=2
sum(2,2)
def sum(a, b=2):
return a + b
Here are a couple of examples where we don't specify b
and it takes on the default value, i.e. b=2
print(sum(2))
print(sum(4))
The default value can always be overwritten.
sum(2, b=3)
Specificially, *var_args
is a variable positional argument.
def sum(*var_args):
ans = 0
for i in var_args:
ans += i
return ans
We can now call the function with any number of arguments and they will be summed accordingly.
sum(1,2)
sum(1,2,3,4)
sum(1,2,3,4,100)
Variable keyword arguments
We can also have variable keyword arguments. These utilize the special syntax of **kwargs
. The keyword arguments are passed into the function as a Python dictionary. For example, a function with the signature:
a_keyword_arg_function(**kwargs)
That is called with
a_keyword_arg_function(a=1, b=2, c='three')
will have a variable available for use inside the function
kwargs = {'a': 1, 'b': 2, 'c'='three'}
Let's show an example in code:
def keyword_arg_function(**kwargs):
for key, value in kwargs.items():
print('keyword: {} with value = {}'.format(key, value))
keyword_arg_function(name1='Romeo', name2='Juliet')
f = lambda x: x + 2
The function can then be called like any normal function.
f(2)
Lambda functions can have more than one variable and can also have keyword arguements as well.
g = lambda x, y=2: x + y
print(g(2))
print(g(2,2))
Further Reading
Further reading on functions can by found in the Python documentation.