Related Tags

communitycreator
python

# How to generate a triangle using asterisks in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate a hollow equilateral triangle using asterisks in Python.

We can print a plethora of patterns using Python. A prerequisite for doing so is to have a good understanding of how loops work in Python.

Here we will be using simple for loops to generate a hollow equilateral triangle.

### Description

A triangle is said to be equilateral if all three of its sides are of the same length.

To display the triangle in Python, we will be using two for loops nested within an outer for loop:

• An outer loop to handle the number of rows.
• Two inner loops to handle the number of columns.

### Code

Let’s look at the code snippet below.

def hollow_triangle(n):

# Outer loop for rows
for i in range(1,n+1):

# Inner loop for columns
for j in range(1,2*n):

# Conditions for creating the pattern
if i==n or i+j==n+1 or j-i==n-1:
print("*", end="")
else:
print(end=" ")
print()

hollow_triangle(8)



### Explanation

• In line 4, we create a for loop to handle the number of rows.
• In line 7, we create a nested for loop to handle the number of columns.
• In lines 10 to 13, we defined the conditions for creating the required shape.
• In line 14, we use print() to move to the next line. The entire code has been enclosed inside the function block hollow_triangle, which takes the row size as an argument.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time