Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to generate an equilateral triangle using stars in Python

Vinisha Maheshwari

We can use Python to print different patterns once we are familiar with loops.

Here, we use simple for loops to generate equilateral triangles using stars.

This is also known as the Pyramid Pattern.

The primary purpose of creating this program is to explain the concept of the loop in Python programming.

Description

Clarity about the features that make up an equilateral triangle is necessary. A triangle is said to be equilateral if it has 3 sides that are all the same length.

To execute this by means of a program, we need two loops.

  • Outer loop: We use this to handle the number of rows.
  • Inner loop: We use this to handle the number of columns.

Code

def triangle(n):
  k = n - 1
  for i in range(0,n):
    for j in range(0,k):
      print(end = " ")
    k -= 1
    for j in range (0, i+1):
      print("* ", end='')
    print("\n") 

n = int(input())
triangle(n)

Enter the input below

Create an Equilaternal Traingle using Stars in Python

Explanation

  • In line 1, we create a function where n is the number of stars per side.

  • In line 2, we define k that denotes the number of spaces.

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

  • In line 4, we use the inner loop to create spaces.

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

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

  • In line 8, we print star to generate an equilateral triangle using stars.

    Note: Instead of star, we can use any other symbol.

  • In line 9, we use \n to print the stars from the next row.

Now, based on the value of n, we can create triangles of any size.

Although the program above addresses our needs, it isn’t an optimal solution. It contains Nested Loops, which increase time and space complexity significantly.

Therefore, an optimal solution for the same issue is as follows.

Code

def triangle(n):
   for i in range(1, n+1):
      print(' ' * n, end='')
      print('* '*(i))
      n -= 1
n = int(input())
triangle(n)

Enter the input below

Create an Equilateral Traingle using Optimized Approach

Explanation

  • In line 1, we create the function.

  • From line 2, we create a single for loop wherein both operations of row and column are utilized.

  • In line 3, we use space n times to create the pointing end of the triangle, and n is reduced after each iteration.

  • In line 4, we print star i times which increases by 1 (from 1 to n+1) in each iteration.

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

When we manipulate the print statement, we can create different patterns, such as number or alphabet patterns.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring