- 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
How to create a triangle using Python for loop?
There are multiple variations of generating triangle using numbers in Python. Let's look at the 2 simplest forms:
for i in range(5): for j in range(i + 1): print(j + 1, end="") print("")
This will give the output:
1 12 123 1234 12345
You can also print numbers continuously using:
start = 1 for i in range(5): for j in range(i + 1): print(start, end=" ") start += 1 print("")
This will give the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
You can also print these numbers in reverse using:
start = 15 for i in range(5): for j in range(i + 1): print(start, end=" ") start -= 1 print("")
This will give the output:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Advertisements