Default Parameter ValuesΒΆ
It is sometimes useful to assign a default value to a parameter. This can be done by setting the parameter equal to the desired default value in the function definition. When the function is called, if an argument is supplied for this parameter, it will override the default value. If no argument is supplied for a parameter with a default value, then the default will be used.
def sum_first(arg_list, n=5):
total = 0
for i in range(n):
total += arg_list[i]
return total
my_list = [4, 8, 5, 7, 4, 9, 1, 6, 3, 2]
print(sum_first(my_list, 3))
print(sum_first(my_list, 5))
print(sum_first(my_list))
17
28
28
If the argument supplied for n
in the sum_first()
function is greater than the length of the list, then the function will result in an error. We will now rewrite this function so that it instead retuns the sum of all of the elements in the list in this situation.
def sum_first(arg_list, n=5):
total = 0
m = min(n, len(arg_list))
for i in range(m):
total += arg_list[i]
return total
print(sum_first(my_list, 15))
49