-1

I am writing a function of Python would like to sum all the number in a tuples but it.s get wrong after run

def sumall(*x):

   sm=0

   for i in len (x):
      sm= x[i] + sm

   print sm

It.s contain into object is not iterable error when I input

sumall (1,2,3)

Please help me

adder
  • 3,512
  • 1
  • 16
  • 28

3 Answers3

3
def sumall(x):
   return sum(x)

sumall((1, 2, 3))
pylearner
  • 537
  • 2
  • 8
  • 26
0

As pydev answered, there is a builtin sum method which does exactly what you asked. So, you better use it. But if you are doing this code for exercise, you have few issues

def sumall(*x):
   sm=0
                      .<---- there shouldn't be space between len and (x) and range is required
   for i in range(len(x)):
      sm= x[i] + sm  <---- this can be converted to sm += x[i] which appends

   print sm

len is returning an int which isn't iterable. range on the other hand does.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
0

Your problem is that the syntax of for x in l takes l as an iterable - list, tuple, etc.

The statement len(x) returns an integer, which isn't by any means an iterable.

You should simply loop over x.

def sumall(*x):
    sm=0

    for item in x:
        sm= item + sm

    print sm

However, in cases when you do need to loop by index (e.g. when your'e looping over two iterables at once) you can use range(), which returns a list of numbers (from 0 to the specified number) you can loop over.

def sumall(*x):
    sm=0

    for i in range(len(x)):
        sm= x[i] + sm

    print sm
Neo
  • 3,534
  • 2
  • 20
  • 32