Related Tags

communitycreator
python

# How to generate a left-angled triangle using stars in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate a left-angled triangle using stars in Python.

We can print a plethora of patterns using Python. The basic and only prerequisite to do this is a good understanding of how loops work in Python. In this shot, we will be using a simple for loops to generate a right-angled triangle using stars.

### Description

A triangle is said to be left-angled if it has an angle equal to 90 degrees on its left side.

To execute this using Python programming, we will be using two for loops nested within an outer for loop:

• An outer loop to handle the number of rows.
• Two inner loops, one to handle the initial spaces and the other to print the characters.

### Code

Let’s have a look at the code.

# Number of rows
rows = 5

# Iterating value for column
k = 2*rows-2

# Loop through rows
for i in range(rows):

# Loop to print initial spaces
for j in range(k):
print(end=" ")

# Updating value of K
k = k-2

# Loop to print the stars
for j in range(i+1):
print("*", end=" ")
print()

### Explanation

• In line 2, we take the input for the number of rows (i.e., length of the triangle).

• In line 5, we create the iterating variable k, which will be used later to handle the number of columns.

• From lines 8 to 20, we create the outer for loop to iterate through the no of rows.

• In lines 11 and 12, we create the first inner nested loop to print the initial spaces.

• In line 15, the value of k is updated so that the output is a right-angled triangle, i.e., the characters are printed from right to left. Unless updated, the triangle would have been a left-angled triangle.

• In lines 18 and 19, we create our second inner nested loop to print the characters (here, *). The end statement helps us to be on the same line until the loop finishes.

• In line 20, we use print(), to move to the next line.

In this way, we can generate a left-angled triangle using stars in Python.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 