Read n and print 1 + 2 + ... + n. Use a for loop.
What to build
A loop that builds up a total.
Requirements
- Read
n. - Add up the numbers from 1 to
nwith aforloop and print the result.
Input
One whole number n from 1 to 10000.
Output
The sum.
Constraints
n is from 1 to 10000.
Example
Input:
4
Output:
10
Why it works
range(1, n + 1) includes n itself, because range stops before its second value.
Examples
Example 1 · Input
4
Expected output
10
Example 2 · Input
1
Expected output
1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
range(1, n + 1) gives 1, 2, ..., n.
Hint 2
Print the total once, after the loop.
Solution
Show one correct solution (try it yourself first)
n = int(input())
total = 0
for i in range(1, n + 1):
total = total + i
print(total)