How to find sum of a given Range of Integers using Python?

Python’s range() function can be used alongwith sum() function for summing up a range of Integers. For example => If you want to find sum of numbers from 1 to 50 then this is the approach to go. But if in case, you’re concerned about Performance of program then this way of finding sum is not appropriate as its time complexity is O(n) where n is range. So as range increases, time complexity also increases. Anyway, just keep in mind that this is not best performing approach for finding sum of a range of integers.

Python Code for Finding Sum of Range of Integers

start = 1 # Start of your range 
end = 10 # End of your range 
num_list = range(start, end + 1) # List of all numbers in given range 
final_sum = sum(num_list) 
print("Final Sum =", final_sum)
 
#Combining all of it together in a single line 
print("Final Sum =", sum(range(start, end + 1)))

Output

Final Sum = 55
Final Sum = 55

This is simplest but time expensive algorithmic approach which can be taken for summing range of integers using Python Programming Language.

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts