Search code examples
python-3.xfunctionargs

python function help - why am I only getting the first number in the argument when I execute the function


Here is the code I'v tried, I don't understand why I am getting only the first argument (1) when I execute the program

def add(*args):
   total = 0
    for a in args:
      total += a
      return total

sum1 = add(1, 2, 3)
 print(sum1)

result: 1 (only the first argument)


Solution

  • You are not just getting the first argument. The problem is that your return statement is in the for loop and will execute after the first occurrence of the loop. Unindent your return statement so it runs after the for loop finishes

    def add(*args):
        total = 0
        for a in args:
            total += a
        return total
    
    sum1 = add(1, 2, 3)
    print(sum1)