john gachara
last year
Johncountry asked

Why did we use n+1 in the range() function?

Kelish Rai
Expert
last year
Kelish Rai answered

In this code:

def calculate_sum(n):
    
    total = 0
    
    for i in range(n+1):
        total += i
    
    return total
    
result = calculate_sum(100)
print(result)    # 5050

When you pass n to the range() function, it'll only iterate from i = 0 to i = n - 1.

So, to make sure it includes i = n as well, you need to pass n + 1 to the range() function.

This ensures the loop runs all the way from 0 up to n, giving you the desired sum.

Hope this helps. Let me know if you need more help or have further questions. I'm happy to help.

Python
This question was asked as part of the DSA with Python course.