Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

# Generate solid equilateral triangle using alphabets in Python

Vinisha Maheshwari

In this shot, we will generate a solid equilateral triangle using alphabets in Python.

We can print a plethora of patterns using Python. The only prerequisite to do so is a good understanding of how loops work in Python. Here, we will be using simple for loops to generate a solid equilateral triangle using alphabets.

### Description

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

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

### Code

Let’s take a look at the code.

# Number of Rows
n = 8

# Number of spaces
k = n - 1

# Outer loop to handle number of rows
for i in range(0,n):

#Inner loop to handle number of spaces
for j in range(0,k):
print(end=" ")

# Decrementing k after each loop
k -= 1

# Inner loop to handle number of columns
# Values change acc to outer loop
for j in range (0, i+1):

ch = chr(65+i)

# Printing Stars
print(ch, end=" ")

# Ending Line after each row
print("\r")



### Explanation

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

• In line 5, we define k, the number of spaces.

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

• In lines 11 and 12, we use inner loops to create spaces.

• In line 15, the value of k is decremented after every iteration to create the slope.

• In line 19, the loop is created to handle the number of columns.

• In line 21, 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 65 has been used, as the ASCII value of A (start of the triangle) is 65.

• In line 24, we print ch to generate an equilateral triangle using characters.

• In line 27, we use \r to print the stars from the next row.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time