0

I started to learn Python and in exercises about args, I have this block of code, and I don't quite understand why we would define sum as 0 and then i as sum +=

def add(*args):
    sum = 0
    for i in args:
        sum += i
    return sum

Thanks for help!

Anna
  • 3
  • 2
  • 2
    (1) Suppose `args` is empty. Then the sum of the arguments is zero. (2) Suppose it is not empty. If you don't start with `sum=0` then you will have to treat the first argument as different from all of the others: assign the first, then add the others. – BoarGules Aug 11 '21 at 19:28
  • 2
    If you don't set `sum` to `0` first, how are you going to add each argument to it? – Barmar Aug 11 '21 at 19:28
  • btw `sum+=1` is just `sum = sum+i`, where sum is incremented by i – sahasrara62 Aug 11 '21 at 19:36
  • fwiw, `sum()` is a built-in function. 1) You can just use that 2) Don't name your own variables the same as built-ins – OneCricketeer Aug 11 '21 at 19:43
  • I don't think the proposed duplicate has anything to do with what the OP is asking. – chepner Aug 11 '21 at 19:44
  • 1
    We will never understand what the OP is asking until they respond. Everything else is speculation. – quamrana Aug 11 '21 at 19:45

2 Answers2

0

*args let's you send an undefined amount of arguments as a tuple. At the beginning of the function, where you want to obtain the sum, it's obviously 0 and then you update the value.

You can also write sum+=i as:

sum=sum+i

Let's do an small example, you do:

add(1,2,3)

It would look like:

  1. You enter the function, sum is 0.
  2. You iterate for every element of args (1,2,3).
Iteration 1: sum=0, i =1, sum=sum+i = 1

Iteration 2: sum=1 (updated last iteration doing 0+1) and i 2, we have sum=sum+i=3

Iteration 3 is 3+3 = 6

Whats the advantage of using *args? Being able to send as many elements as you want without needing to modify the function.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Alejandro A
  • 1,150
  • 1
  • 9
  • 28
0

We'd like the following to be true when there is at least one argument:

add(x1, x2, ..., xn) == x1 + add(x2, ..., xn)

Eventually, though, we reach this case:

add(x1) == x1 + add()

What should add return with no arguments? Since add(x1) should clearly equal x1, we have to define add() == 0. This is because 0 is the identity for addition: x + 0 == x for any value of x.

Since your loop won't be entered at all when there are no arguments, we need to initialize sum = 0 so that after we skip the loop, return sum will return 0 as required.

The loop itself is just adding numbers one after the other. If args is 1,2,3,4 then the function is equivalent to

sum = 0
sum += 1  # 0 + 1 == 1
sum += 2  # 1 + 2 == 3
sum += 3  # 3 + 3 == 6
sum += 4  # 6 + 4 == 10
return sum     # return 10
chepner
  • 497,756
  • 71
  • 530
  • 681