Python Pattern Programs

Python Program To Print Hollow Triangle Pattern

Last updated June 9, 2023 by Jarvis Silva

In this tutorial we will see the python program to print hollow triangle pattern, printing patterns in python is fun and very interesting, you must have created python programs to print diamond and other shapes but today I will show you how to print a hollow triangle pattern.

We will use for loops for creating this pattern so no external python library is needed, just follow this tutorial till the end.

Python Code To Print Hollow Triangle Pattern

row = 10

for i in range(row):
    for j in range(row-i):
        print(' ', end='')
    for j in range(2*i+1):
        if j==0 or j==2*i or i==row-1:
            print(' ', end='')

Above is the code for printing the hollow triangle pattern, now let’s see how this code works:

  • The variable row is set to 10, indicating the number of rows in the pyramid.
  • The outer loop iterates row number of times to represent each row of the pyramid.
  • Within the outer loop, the first inner loop iterates row - i times and prints spaces to create the indentation for each row. The value of i represents the current row number, so the number of spaces decreases by one for each subsequent row.
  • The second inner loop iterates 2*i + 1 times to print the asterisks and spaces within each row. The value of i determines the number of asterisks in each row. The conditions inside the loop check whether the current position (j) is at the beginning or end of the row (j == 0 or j == 2*i) or if it is the last row of the pyramid (i == row-1). If any of these conditions are true, an asterisk is printed; otherwise, a space is printed.
  • After each row is printed, a newline character is printed using the print() function without any arguments. This moves the cursor to the next line, creating a new row in the pyramid.
  • The outer loop continues to iterate, repeating the process for each row until all rows of the pyramid have been printed.

Now to run this program you need to have python installed on your computer, If you don’t have then follow this guide: Install and setup python on your computer or you can use this online python compiler.

After running this program you will see a hollow triangle pattern printed like below output.

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

As you can see we successfully created this program, I hope you found this tutorial helpful and useful. Do share this tutorial with your friends who might be interested in this program.

Here are some more python drawing tutorials for you:

I hope you found what you were looking for from this tutorial, and if you want more python programs and tutorials like this, do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂