Programs for printing pyramid patterns in Python


Taking advantage of the for loop and range function in python, we can draw a variety of for pyramid structures. The key to the approach is designing the appropriate for loop which will leave both vertical and horizontal space for the position of the symbol we choose for drawing the pyramid structure.

Pattern -1

We draw a right angle based pattern.

Example

 Live Demo

def pyramid(p):
   for m in range(0, p):
      for n in range(0, m+1):
         print("* ",end="")
      print("\r")
p = 10
pyramid(p)

Output

Running the above code gives us the following result −

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *

Pattern-2

We make a 180 degree rotation to the above pattern.

Example

 Live Demo

def pyramid(p):
   X = 2*p - 2
   for m in range(0, p):
      for n in range(0, X):
         print(end=" ")
      X = X - 2
      for n in range(0, m+1):
         print("* ", end="")
      print("\r")
p = 10
pyramid(p)

Output

Running the above code gives us the following result −

                  *
                * *
              * * *
            * * * *
          * * * * *
        * * * * * *
      * * * * * * *
    * * * * * * * *
  * * * * * * * * *
* * * * * * * * * *

Pattern-3

In this case we draw a triangle shape of type isosceles. Both the sides of the triangle are of equal length.

Example

 Live Demo

n = 0
r = 12
for m in range(1, r+1):
   for gap in range(1, (r-m)+1):
      print(end=" ")
   while n != (2*m-1):
      print("* ", end="")
      n = n + 1
   n = 0
   print()

Output

Running the above code gives us the following result −

                      *
                    * * *
                  * * * * *
                * * * * * * *
              * * * * * * * * *
            * * * * * * * * * * *
          * * * * * * * * * * * * *
        * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *

Pattern-3

Now we draw a case of triangle in which all the three sides are equal. Also called equilateral triangle.

Example

 Live Demo

length = 12
k = (2 * length) - 2
for p in range(0, length):
   for n in range(0, k):
      print(end=" ")
   k = k - 1
   for n in range(0, p + 1):
      print("@", end=' ')
   print(" ")

Output

Running the above code gives us the following result −

           @
          @ @
         @ @ @
        @ @ @ @
       @ @ @ @ @
      @ @ @ @ @ @
     @ @ @ @ @ @ @
    @ @ @ @ @ @ @ @
   @ @ @ @ @ @ @ @ @
  @ @ @ @ @ @ @ @ @ @
 @ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ @ @ @ @ @
raja
Published on 04-Feb-2020 07:26:51
Advertisements