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.
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:
Let’s have a look at the code.
# Number of rowsrows = 5# Iterating value for columnk = 2*rows-2# Loop through rowsfor i in range(rows):# Loop to print initial spacesfor j in range(k):print(end=" ")# Updating value of Kk = k-2# Loop to print the starsfor j in range(i+1):print("*", end=" ")print()
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.