2

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?

4 Answers 4

3

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Code only answers are not as helpful as those which explain: 1) Why the OPs code doesn't work and 2) Why yours does.
or return abs((num1 * (num1 + 1) // 2) - (num2 * (num2 + 1) // 2))
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.