Counting the numbers of input parameters in a function

Hello everyone!
Hope you’re having a great day.

I’m taking classes on Python 3 (my very first programming language!) and just finished the optional code challenges, more precisely the Averages one. Link down below.

https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-functions

The challenge asks to find average value of 2 input parameters, num1 and num2. Since the number of inputs is constant 2, dividing the sum by 2 is straightforward but I kept thinking.

What if the number of inputs changed throughout the code?

So I tried to write a code like:
Def average(num1, num2):
Return (num1 + num2) / len(average)

Which didn’t work. :sweat_smile:

Is there a way to count the numbers of inputs to use inside of the function later on?

Thank you for you time!

Hi,
Well done for thinking ahead. Your issue is your function is set up to always take two parameters.
You could alter it to take in one list, add each of the elements together and then use the length of the list to find the average;
e.g. something like

def average(nums):
  total = 0
  for num in nums:
    total += num
  return total / len (nums)

hope that helps

2 Likes

This may not be what you are wanting to know, but it might come in handy when multiple arguments are given with no limit to their number:

def count_args(*args):
    print (sum(args))
    return len(args)

count_args(1,2,3,4,5,6,7,8,9)
45
9

The splat (*, as it is known in Ruby and other languages) is an unpacking tool that spreads over the entire arguments sequence. Undemarcated sequences in Python are treated as tuples.

2 Likes