Related Tags

communitycreator
python

# Generate a hollow equilateral triangle using alphabets in Python

Vinisha Maheshwari

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

We can print a plethora of patterns using Python. The only prerequisite for this is having a good understanding of how loops work in Python. Here, we will use simple for loops and alphabets to generate a hollow equilateral triangle.

### Description

A triangle is said to be equilateral if it has all 3 sides of the same length. To create an equilateral triangle with alphabets using Python programming, we will use 2 for loops:

• An outer Loop: To handle the number of rows.
• An inner loop: To handle the number of columns.

### Code

Let’s look at the code for this:

# Number of Rows
n = 8

if n > 26 or n < 3:
print("""
The value of n should be less than 26 as there are 26 alphabets and
\ngreater than 3 as that's the smallest hollow triangle that can be made.
""")
else:
# Outer loop for rows
for i in range(1,n+1):

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

ch = chr(64+i)

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

### Explanation

In the code given above:

• In line 2, we take the input for the number of rows.

• From lines 4–5, we check whether the value of n is less than 26 or greater than 3. If it exceeds 26, then we will not proceed further and print a message. This is done to ensure that only 26 alphabets are used to generate the pattern. Similarly, if the value is less than 3, then the triangle will not be hollow.

• In line 9, we create a for loop to handle the number of rows.

• In line 12, we create a nested for loop to handle the number of columns.

• In line 14, we define ch which is used to create alphabets from numbers by using the iterative value of i and the concept of ASCII conversion. The starting value 64 + (i=1), is used as the ASCII value of A (starting of the triangle), which is 65.

• From lines 17–22, we define the conditions for creating the required shape:

• i==n ⇒ is used to print the base of the triangle.
• i+j==n+1 ⇒ is used to print the left side of the triangle.
• j-i==n-1 ⇒ is used to print the right side of the triangle.
• In line 22, we use the print() function to move on to the next line.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 