- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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.
Advertisements