-2

I am currently a beginner in python, why is my function not returning the arguments added together? here is my code:

def add(*numbers):
    total = 0
    for number in numbers:
        total = total + number
        return(total)

I use the function as below.

add(9,9,9)

I get the output.

9
Amit
  • 2,018
  • 1
  • 8
  • 12
Boyzie
  • 1
  • 2
  • 2
    Welcome to StackOverflow! Please read [this](https://meta.stackoverflow.com/a/285557/1941241) and then add your code to your question as code, rather than an image. – rickdenhaan Jan 25 '21 at 14:07
  • 1
    Does this answer your question? [Stuck with loops in python - only returning first value](https://stackoverflow.com/questions/52118391/stuck-with-loops-in-python-only-returning-first-value) – rickdenhaan Jan 25 '21 at 14:08
  • Your `return` statement is indented too far, align it with the `for`. – Rick M Jan 25 '21 at 14:09
  • **We don't allow images of text (code/input/output/errors, or otherwise) on Stack Overflow.** Please post your code as ([formatted](https://stackoverflow.com/editing-help)) text. Read more [here](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). Questions with images of text/code/errors are routinely closed. Please also check out the [tour](https://stackoverflow.com/tour) and the question guide [here](https://stackoverflow.com/help/how-to-ask) to make sure this & your future questions are suitable for this Q&A. – costaparas Jan 25 '21 at 14:43

4 Answers4

0

You have a problem with indentation.

Try this:

def add(*numbers):
    total = 0
    for number in numbers:
        total = total + number

    return (total)
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

Currently, your code returns total after one run of the add function, move the return(total) one tab backwards, for example, your code should look like:

def add(*numbers):
   total = 0
   for the number in number:
        total += number
   return total
Hunter
  • 321
  • 2
  • 11
0

Adjust the indentation of the line return(total). Right now it just returns the first number without ever looking at the others.

this should work:

def add(*numbers):
    total = 0
    for number in numbers:
        total+=number
    return total
Ingumeta
  • 51
  • 1
  • 8
0

As others have stated in their answers, you have an intentation problem. Since there are no ; nor {}, Python is very sensitive to indentation to define the limits on functions... everything, really.

Try:

def add(*numbers):
    total = 0
    for number in numbers:
        total = total + number
    return (total)
Andrew
  • 121
  • 6