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.
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.
Is there a way to count the numbers of inputs to use inside of the function later on?
Thank you for you time!
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
total = 0
for num in nums:
total += num
return total / len (nums)
hope that helps
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:
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.