Python Program to read a number and print the number summation pattern


April 9, 2022, Learn eTutorial
1195

In this simple python program, we need to print a summation pattern. It's a pattern python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is the summation pattern?

In this pattern, the Python program read a number and print the summation pattern. The Summation pattern is a sum pattern of that number. Suppose we have a number 4 then the summation pattern of the 4 is.

1 = 1

1 + 2 = 3

1 + 2 + 3 = 6

1 + 2 + 3 + 4 = 10

How to find the summation pattern of a number in python?

To apply this logic in the python language, we have to use two nested for loops. We use the First loop to take one number and use the Inner for loop to print that number's summation pattern. The Outer loop will take all iterations till the number, and for each number, the inner for loop prints the summation pattern of that number using an if condition in python. Finally, we append each summation pattern of the number into the python list and use the sum() method to calculate the sum.

ALGORITHM

STEP 1: Accept the user's input using the input method and convert the string to an integer using int() in the Python programming language.

STEP 2: Use the outer for loop to take each element from one to the given number. And initialize a python list.

STEP 3: Use the inner for loop from one to the element in the outer loop and print the element i and add a space using sep parameter and use end= parameter.

STEP 4: Use the if condition to check element in the inner for loop i is less than the element in outer for loop j.

STEP 5: Use the print statement to print  + and use the sep parameter for printing space and end=.

STEP 6: Append the elements into a python list using the append method in python language,

STEP 7: Print the sum, which is calculated by using the sum() method.

Python Source Code

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

OUTPUT

Enter a number: 4
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10