Python Coding Lab: Sum of First n Numbers

Sum of First n Natural Numbers

This training module demonstrates how to efficiently calculate the sum of all whole numbers from 1 up to a user-specified number n. Instead of using a resource-heavy loop that adds numbers one by one, this program utilizes a famous mathematical formula.

The Efficiency Formula: S = [n * (n + 1)] / 2

Why use the formula? A loop takes O(n) time (it slows down as n grows). The formula executes in O(1) constant time, meaning it calculates the sum instantly whether n is 10 or 10,000,000.


Python Implementation

Review the commented source code below to understand the step-by-step execution.

# This program calculates the sum of numbers from 1 to n using the arithmetic series formula.
# Step 1: Prompt the user to input a number, convert that string input into an integer, and store it in variable 'n'.
n = int(input("Enter a number (n): "))

# Step 2: Apply the mathematical formula n * (n + 1) / 2 to find the sum.
# We use standard division (/) and wrap the result in int() to convert the final output back into a clean whole number.
total_sum = int((n * (n + 1)) / 2)

# Step 3: Print the final result to the console using an f-string to format the output clearly.
print(f"The sum of numbers from 1 to {n} is: {total_sum}")

Training Test Cases

Use these sample scenarios to verify your program's behavior during execution testing.

Test Scenario Sample Input (n) Expected Console Output Mathematical Verification
Small Integer 5
The sum of numbers from 1 to 5 is: 15
(5 * 6) / 2 = 15
Baseline / Minimum 1
The sum of numbers from 1 to 1 is: 1
(1 * 2) / 2 = 1
Large Scale Integer 100
The sum of numbers from 1 to 100 is: 5050
(100 * 101) / 2 = 5050

Comments