When it is required to read a number and print the pattern of summation of natural numbers, a simple ‘for’ loop can be used.
Below is a demonstration of the same −
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
Explanation
A number is taken as input from the user.
This number is iterated over.
An empty list is defined.
Another ‘for’ loop is initiated.
The separator is specified as ‘’.
If the value of inner iterator is less than value of outer iterator, the ‘+’ is used.
These values are appended to the empty list.
Their sum is computed and displayed as the output.