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.
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
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()
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:
In line 22, we use the
print() function to move on to the next line.
View all Courses