# Sum of Integers in A Range in Python

In this tutorial, we will be finding the sum of natural numbers in the range given by the user. We will be using a for loop to find the same. To calculate the sum of integers in a range in Python we will be using the following concepts:

- Python if…else Statement
- Loops in python

### Sum of Integers

We will be taking the lower bound and upper bound of the range from the user. All the integers within this range will be added.

**NOTE:** The lower bound and the upper bound are also included in the sum, i.e. the sum is inclusive of the ends.

lower = int(input("Enter lower bound of range: ")) upper = int(input("Enter upper bound of range: ")) sum = 0 for i in range(lower, upper + 1): sum = sum + i i = i + 1 print("Sum is ", sum)

First, we ask the user to input the lower and upper bound of the range using * int(input(“Enter lower bound: “)) *and

*. Here,*

**int(input(“Enter upper bound: “))***prints the message on the console and also reads the input given as a string. But we want the input to be an*

**input()***so that we can perform mathematical operations on them and for that, we use*

**int***.*

**int()**We then initiate * sum *as 0, so that we can use it later while finding the sum. It is also important as it tells that

*is of integer type.*

**sum**Range in for loop includes the lower limit but excludes the upper limit. So we will start the loop which will find the sum within the range (inclusive). We set the limits of the loop as * lower and upper + 1*. Inside the loop we are just adding the numbers in the range to

*.*

**sum**After the loop finishes execution we display the sum using * print()*.

### Output

Enter lower bound of range: 4 Enter upper bound of range: 7 Sum is 22 #Sum is 4+5+6+7 = 22

So, here it is a simple program to find the sum of integers within a range inclusive with Python programming language.

Also read,

- How to find all the possible proper divisor of an integer in Python3
- How to find all Sundays of a calendar year in Python

Hello,

Thank you for the tutorial.

When I run your example with lower equal to 1 and upper equal to 0, I get the result 0. Isn’t the expected output supposed to be 1?

Likewise, when I enter 0 as lower and -1 as upper, I get 0 instead of -1.

How can I tweak the code to get the expected outputs?

Thank you for your time,

Buck