Ask coding questions

← Back to all posts
I do not understand how to

There is a problem: Sum of Consecutive Numbers (Python)

No one likes homework, but your math teacher has given you an assignment to find the sum of the first N numbers.

Let’s save some time by creating a program to do the calculation for you!

Take a number N as input and output the sum of all numbers from 1 to N (including N).

Sample Input

Sample Output

Explanation: The sum of all numbers from 1 to 100 is equal to 5050.

I wrote some code, but it did not work. After some research I found this code(it works):
N = int(input())
for i in range(1,N+1):


Can someone explain me this? (This is a problem from Sololearn PythonForBeginners>Lists>CodeProject36)

Answered by IMayBeMe [earned 5 cycles]
View Answer

Lets go through this code step by step:

The code above prompts the user to input an integer which in this case will set the upper bound for all the numbers being added.

Now, this doesn't do much apart from setting up some variables which will be used later on. Then comes the for loop like this:

This is the main driving force of the code. What it does is it runs the code N times and each time it makes count equal something one higher like this: 1, 2, 3, and so on. Then it adds count to the final sum and continues the loop. I just want to say this code isn't really the best and there are much better ways to do it like this:

The code above is much more self-explanatory and is overall just a lot cleaner.


It asks for a number, and stores it in the variable N. Then for each number up to N, it adds 1 to the variable count. Then it prints out count.