How to generate a hollow right-angled triangle in Python
In this shot, we will discuss how to generate a hollow right-angled triangle with stars in Python.
We can print a plethora of patterns with Python. The basic and only prerequisite is a good understanding of how loops work in Python.
Here, we will use simple for loops to generate a hollow right-angled triangle with stars.
Description
A triangle is said to be right-angled if it has an angle equal to 90 degrees on its left side.
We will use 2 for loops:
- Outer loop: To handle the number of rows.
- Inner loop: To handle the number of columns.
# Number of rowsn = 5# Loop through rowsfor i in range(1, n+1):# Loop through columnsfor j in range(1, n+1):# Printing Patternif (i == j) or (j == 1) or (i == n):print("*", end=" ")else:print(" ", end=" ")print()
Explanation
-
In line 2, we take the input for the number of rows (i.e. the length of the triangle).
-
In line 4, we create a
forloop to iterate through the number of rows. -
In line 6, we create an inner nested
forloop to iterate through the number of columns. -
From lines 8 to 11, we use conditional statements to create the pattern. The end statement helps to stay on the same line.
-
In line 12, we use the
print()statement to move to the next line.