Natural summation pattern in Python

In this tutorial, we will learn how to print the natural summation pattern in Python. We will take natural number as input and the program will print the summation pattern.

This is a simple program that takes an integer input (say, n) and prints the natural summation pattern for that natural number.

Let’s have an example:

Suppose the input number is 7.
The output will be like:
      1 = 1
      1 + 2 = 3
      1 + 2 + 3 = 6
      1 + 2 + 3 + 4 = 10
      1 + 2 + 3 + 4 + 5 = 15
      1 + 2 + 3 + 4 + 5 + 6 = 21
      1 + 2 + 3 + 4 + 5 + 6 + 7 = 28

Print natural summation pattern in Python

Approach:

We will keep a record of the previous string and in every iteration, we update the string and print it. Let’s jump into the code.

Python Code:

# function to print pattern
def print_natural_sum(n):

    last = "1"
    total = 1
    
    # print for 1
    print(last, "=", total)

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

        # update the string and print it
        last += " + " + str(i)
        print(last, "=", total)


if __name__ == '__main__':

    # take input for a natural number
    n = int(input("Enter a natural number : "))

    # function call
    print_natural_sum(n)

Output:

Enter a natural number : 5

 

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15

Also read:

Iterative Pair Pattern in Python

Phyllotaxis Pattern in Python

Leave a Reply

Your email address will not be published. Required fields are marked *