How to Draw an Equilateral Triangle in Python
by Prostyle4444 in Circuits > Software
380 Views, 1 Favorites, 0 Comments
How to Draw an Equilateral Triangle in Python

In this program, we will write a simple program to draw an equilateral triangle using only the ASCII character * and some array logic. Let's get started.
Supplies

You would need the latest Python compiler and a Python IDE installed. If you do not have them, I highly recommend installing Thonny. Thonny is a simple IDE that installs the latest Python version on your system. Thonny also runs in on multiple operating systems.
Getting the User Input

We get the user input using Python's input() command in this step. We check if the input is greater than 1 otherwise we exit the program. Here is the code for the above logic:
side = int(input("Enter the side of the triangle: "))
curr_num = 0
if side<=1:
exit()
Now we will be using Array logic to print our equilateral triangle. I'll initially post the code for the array logic and then explain more in-depth.
Adding Array Logic (CODE)

for i in range(side):
for j in range(side):
if (i== side - j) or ((i == side - 1) and (j%2 != 0)):
print("*", end="")
else:
print(" ", end="")
for k in range(side):
if (i == k) or ((i == side - 1) and (k%2 == 0)):
print("*", end="")
else:
print(" ", end="")
print("")
Array Logic (Explanation)
for i in range(side):
for j in range(side):
if (i== side - j) or ((i == side - 1) and (j%2 != 0)):
print("*", end="")
else:
print(" ", end="")
for k in range(side):
if (i == k) or ((i == side - 1) and (k%2 == 0) and (k != side -2)):
print("*", end="")
else:
print(" ", end="")
print("")
In the above code, we run two arrays within a main array. The first sub-array draws the left part of the triangle, while the second sub-array draws the right part of the array. The last part of the code i.e. print("") also prints a newline along with the null character and takes care of printing a newline every iteration.
The loop divides the parts of the side of a triangle as odd and even using the Modulo (%) operator. You'll understand the code better as you try this code in your own IDE.
Complete Code for the Project

I've attached the complete code of the project below. I've also added the code in the body below.
side = int(input("Enter the side of the triangle: "))
curr_num = 0
if side<=1:
exit()
for i in range(side):
for j in range(side):
if (i== side - j) or ((i == side - 1) and (j%2 != 0)):
print("*", end="")
else:
print(" ", end="")
for k in range(side):
if (i == k) or ((i == side - 1) and (k%2 == 0) and (k != side -2)):
print("*", end="")
else:
print(" ", end="")
print("")
Please comment below if you have any doubts. Happy Coding!!