-3

I'm trying to write a function where the user gives the start and end of a range and the output is that range summed. This is my best try:

def sum_range (start, end):
    output = 0
    userange = range(start, end)
    for i in userange :
        sum(i, output)

    return output

I get the following error:

TypeError: 'int' object is not iterable

Mohd
  • 5,523
  • 7
  • 19
  • 30
  • 3
    Try replacing `sum(i,output)` with `output += i`. It will add `i` to the current value of `ouput` – Nuageux Aug 25 '17 at 12:39
  • 1
    Tip: virtually no function in Python accepts an output argument. Results are always *returned*. – deceze Aug 25 '17 at 12:41

3 Answers3

3

You probably don't need to build a range object. Simply take the sum of an arithmetic progression:

def sum_range(start, end):
    return (end - start) * (start + end - 1) // 2


print(sum_range(4, 30))
# 429.0
assert sum_range(4, 30) == sum(range(4, 30))
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • the only thing that's different is the datatype of the result returned (`float` vs `int`) – Ma0 Aug 25 '17 at 12:45
  • This presupposes that `start <= end`, which `range` handles implicitly. – chepner Aug 25 '17 at 12:45
  • @Ev.Kounis I added `2.` to handle integer division in Python 2. Nothing to it – Moses Koledoye Aug 25 '17 at 12:47
  • @chepner True. I seem to have assumed that from the OP since they're not passing a stride parameter – Moses Koledoye Aug 25 '17 at 12:47
  • @StefanPochmann I don't see how your point has to do with integer division. Rewriting the same expression as `((start + end - 1)/2) * (end - start)` will lead to problems only in Python 2. – Moses Koledoye Aug 25 '17 at 13:06
  • I'm somewhat surprised that `sum` isn't optimized to recognize when it gets a `range` object to compute the sum directly, instead of iterating. – chepner Aug 25 '17 at 13:06
  • @MosesKoledoye I think the point is, one of `(end - start)` and `(start + end - 1)` is guaranteed to be even, so since the product is computed first, there's no problem with simply dividing by 2. – chepner Aug 25 '17 at 13:07
  • @chepner Right. It's not immediately obvious for someone glancing through tho. – Moses Koledoye Aug 25 '17 at 13:08
  • 1
    @MosesKoledoye That's what comments are for :) – chepner Aug 25 '17 at 13:10
1

You either need:

def sum_range(start, end):
    output = 0
    userange = range(start, end)
    for i in userange:
        output += i

    return output

or

def sum_range(start, end):
    return sum(range(start, end))
quamrana
  • 37,849
  • 12
  • 53
  • 71
1

you can do :

def sum_range(start, end):
    return sum(range(start, end))

example :

>>> def sum_range(start, end):
...     return sum(range(start, end))
... 
>>> sum_range(10,14)
46
Dadep
  • 2,796
  • 5
  • 27
  • 40
  • 1
    Of course, once you boil it down like that… what's the point of `sum_range()` when you can write `sum(range())`…? – deceze Aug 25 '17 at 12:42