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

Updated on: 17-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements