Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Tuple basics
Tuples in functions
12. Variable number of function arguments
Summary

Instruction

Great! In Python, you can also use tuples to pass a varying number of arguments to a function. Consider the following example:

def average_value(*args):
  if len(args) == 0:
    return 0.0
  sum = 0.0
  count = 0
  for arg in args:
    sum += arg
    count += 1
  return sum/count

The parameter in the average_value() function definition is *args. The asterisk sign (*) before the variable name means any number of arguments. Technically, this is a tuple, which means we can use the len() function or a for loop inside the method body.

The average_value() function can now take any number of arguments and return their average. This means that the function will work with any of these invocations:

average_value(1)                   # 1.0
average_value(1, 2, 3)             # 2.0
average_value(34, 89, 243, 982, 9) # 271.4

Exercise

Write a function named min_max_difference. The function should accept any number of arguments and return the difference between the greatest and smallest numbers. If zero or one argument is passed, return 0.

Stuck? Here's a hint!

Inside the function, define two variables: min and max. Initially, both of them should equal args[0]. Then, check each item in args and see if it's greater than max or less than min; update the max or min values accordingly.