Skip to content

script_2.py - Sum of Numbers from 1 to N

Code

Python
#!/usr/bin/env python3
"""Sum of numbers from 1 to N"""

n = int(input("Enter a number: "))
total = 0

for i in range(1, n + 1):
    total += i

print(f"Sum of numbers from 1 to {n} is: {total}")

Explanation

Line 4: n = int(input("Enter a number: ")) - n is integer type, stores upper limit

Line 5: total = 0 - Accumulator variable initialized to 0 (integer type) - Will be updated inside loop - Must exist before loop starts

Line 7: for i in range(1, n + 1): - n + 1 means stop value is dynamic (depends on user input) - If n=5, range is 1 to 5 - Loop variable i iterates through all numbers in range

Line 8: total += i - += is augmented assignment operator (add and assign) - Equivalent to total = total + i - Adds current loop value to running total - total starts at 0, then 0+1=1, then 1+2=3, then 3+3=6, etc. - Each iteration accumulates sum

Line 10: print(f"Sum of numbers from 1 to {n} is: {total}") - Executes after loop completes (not indented under for) - total contains final accumulated sum