In this tutorial, we are going to delve into Python programming to create a unique shape; a hollow triangle. This is a good way to practice your logic and ability to implement control structures in Python.
We’ll go through this step by step and by the end of it, you should be able to not just create a hollow triangle, but potentially any other hollow shape by tweaking the method appropriately.
Step 1: Set the Number of Rows
The first step is to define how many rows you want in your triangle. This will be the input to your program. For this example, let’s assume steps or rows as 5.
Step 2: Define the Control Structure
We will use nested for loops (a loop inside another loop) to outline the structure of our triangle. The outer loop decides the number of rows while the inner loop decides how many stars (*) to print per row.
Step 3: Add Logic for Hollow Triangle
With the structure defined, we now need to adjust our control structure to print a hollow triangle. Essentially, we only wish to print the stars (*) at the boundaries and leave the middle segments as spaces.
Here’s how you would do that with Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Number of steps rows = 5 # Outer loop will handle number of rows for i in range(0, rows): # inner loop to handle number of columns for j in range(0, i+1): # we only print stars (*) at boundaries and leave the middle segment as spaces if j==0 or i==(j+1)-1 or i==rows-1: print("*",end="") else: print(" ",end="") # go to next line after each row print() |
The full Python code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Number of steps rows = 5 # Outer loop will handle number of rows for i in range(0, rows): # inner loop to handle number of columns for j in range(0, i+1): # we only print stars (*) at boundaries and leave the middle segment as spaces if j==0 or i==(j+1)-1 or i==rows-1: print("*",end="") else: print(" ",end="") # go to next line after each row print() |
Output:
* ** * * * * *
Conclusion
And there you have it. You should be able to run this code in any modern Python interpreter. Note that the spaces between the stars (*) are critical to rendering a hollow triangle. Feel free to modify the code to create other hollow shapes and to gain a deeper understanding of Python control structures. Happy Coding!