pythontuplesargumentskeyword-argumentargs

Incorrect number n of *args (Non-Keyword Arguments) at function in for cycle


I'm a noob trying to complete some tasks and got a problem. I have to calc arithmetic mean (I hope it's a correct definition) in function with *args (Non-Keyword Arguments).

So I have this

def avsum(*numbers):
summ = 0
print('Numbers', numbers)    
for n in numbers:
    summ += n
print('Calc', summ)
print('n', n)
print('Numbers', numbers)
result = summ / (n - 1)
return result


print(avsum(2, 3, 4))

All that prints are for just control and understanding what happens. Terminal shows this:

Numbers (2, 3, 4)
Calc 9
n 4
Numbers (2, 3, 4)
3.0

As I was studied that *numbers are non-keyword arguments and they are tuple. So in tuple numbers, I have 3 elements (Numbers (2, 3, 4)) but n is 4 for some reason. I've made arithmetic mean like sum / (n - 1) but it looks like a weird solution. Any ideas why is that happened? Why is n not 3? Thanks for the reply.

UPDATE Thanks for the reply, sorry maybe I'm stupid but I really can't understand how to make code in comments here 'readable'. As I got it right they are cannot be multi-line. This way I add it to question So I had a close task:

array = [1, 2, 3, 4, 5]
    calc = 0
for n in array:
    calc += n
print("Sum", calc)
print("Arithmetic mean", calc / n)
print(n)

And terminal shows this

Sum 15
Arithmetic mean 3.0
5

So in this case there is no such error you are talking about, the array has 5 elements and n is 5. why? Here and there for loop


Solution

  • The value n in the statement for n in enumerate(numbers): is a variable local to the for loop, it doesn't exist outside of the loop, therefore when attempting the statement result = summ / (n - 1), you are most likely getting an error related to an undefined variable n. To correct this error do: result = summ/len(numbers)

    Given that your input is now named array

    array = [1, 2, 3, 4, 5]
        calc = 0
    for n in array:
        calc += n
    print("Sum", calc)
    print("Arithmetic mean", calc / len(array))