Related Tags

python
communitycreator

# How to generate a hollow right-angled triangle in Python

Vinisha Maheshwari

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 rows
n = 5
# Loop through rows
for i in range(1, n+1):
# Loop through columns
for j in range(1, n+1):
# Printing Pattern
if (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 for loop to iterate through the number of rows.

• In line 6, we create an inner nested for loop 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.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time