Python Program to Read a Number n and Print the Natural Numbers Summation Pattern

When it is required to read a number and print the pattern of summation of natural numbers, a simple for loop can be used. This pattern displays progressive sums like "1 = 1", "1 + 2 = 3", "1 + 2 + 3 = 6", and so on.

Example

my_num = int(input("Enter a number... "))
for j in range(1, my_num + 1):
    my_list = []
    for i in range(1, j + 1):
        print(i, sep=" ", end=" ")
        if(i < j):
            print("+", sep=" ", end=" ")
        my_list.append(i)
    print("=", sum(my_list))

print()

Output

Enter a number... 5
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15

How It Works

  • A number is taken as input from the user

  • The outer loop iterates from 1 to the input number

  • An empty list is defined for each row to store numbers

  • The inner loop prints numbers from 1 to the current outer loop value

  • Numbers are separated by "+" except for the last number in each row

  • Each number is appended to the list and the sum is calculated and displayed

Alternative Method Using Mathematical Formula

Instead of using a list to calculate the sum, we can use the mathematical formula for sum of first n natural numbers:

my_num = int(input("Enter a number... "))
for j in range(1, my_num + 1):
    for i in range(1, j + 1):
        print(i, end="")
        if i < j:
            print(" + ", end="")
    
    # Using formula: sum = n*(n+1)/2
    total = j * (j + 1) // 2
    print(" =", total)
Enter a number... 4
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10

Conclusion

This pattern demonstrates progressive summation of natural numbers using nested loops. The mathematical formula approach is more efficient than storing numbers in a list for sum calculation.

Updated on: 2026-03-25T19:07:26+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements