How to generate pyramid of numbers using Python?

PythonProgramming

There are multiple variations of generating pyramids using numbers in Python. Let's look at the 2 simplest forms

Example

for i in range(5):
   for j in range(i + 1):
      print(j + 1, end="")
   print("")

Output

This will give the output

1
12
123
1234
12345

Example

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("")

Output

This will give the output

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Example

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("")

Output

This will give the output

15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
raja
Published on 20-Apr-2018 08:23:53
Advertisements