yoman
yoman

Reputation: 105

How to loop a range with python

This is my question: I have to write a function that accepts 2 integer values as parameters and returns the sum of all the integers between the two values, including the first and last values. The parameters may be in any order (i.e. the second parameter may be smaller than the first).

This is the example of the result:

screenshot

This is what I've tried:

def sum_range(int1,int2):
    count = 0
    for i in range(int1,int2+1):
         count = count + i
    return count

but for this example:

result = sum_range(3, 2)

print(result)

I got the wrong result, can anyone help?

Upvotes: 2

Views: 273

Answers (4)

Ibo
Ibo

Reputation: 4309

You don't really need to use the loop:

def sum_range(int1, int2):
    if int1 > int2:
        int2, int1 = int1, int2
    return sum(list(range(int1,int2+1)))

Example:

result = sum_range(4, 2)
print(result)

Output:

9

Upvotes: 0

Adi219
Adi219

Reputation: 4814

Using loops:

def sum_range(num1, num2):
    sum = 0
    for i in range(min(num1, num2), max(num1, num2) + 1):
        sum += i
    return sum

Note: You could also do:

def sum_range(num1, num2):
    return abs((num1 * (num1 + 1) / 2) - (num2 * (num + 1) / 2))
## This works as you're essentially asking for the difference between two triangular numbers

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

range counts from the first parameter up to (but not including) the second, which means the range is empty if the first is no smaller than the second.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121942

You'll need to swap your variables if int2 is smaller than int1:

def sum_range(int1, int2):
    if int1 > int2:
        int2, int1 = int1, int2
    count = 0
    for i in range(int1, int2 + 1):
         count = count + i
    return count

You don't really need to use a loop here, if you passed your range() to the sum() function, then you can leave the looping and summing to that function:

def sum_range(int1, int2):
    if int1 > int2:
        int2, int1 = int1, int2
    return sum(range(int1, int2 + 1))

Upvotes: 3

Related Questions