In this shot, we will discuss how to generate a right-angled triangle using stars in Python.
We can print a plethora of patterns using python. The basic and only prerequisite for this is a good understanding of how loops work in Python. Here, we will be using simple for
loops to generate a right-angled triangle using stars.
A right-angled triangle must have one angle equal to 90 degrees.
To execute this using Python programming, we will use two for
loops:
Let us see the code snippet below to understand it better.
# Number of rowsrows = 5# Outer loop to handle the rowsfor i in range(rows):# Inner loop to handle the columnsfor j in range(i + 1):# Printing the patternprint("*", end=' ')# Next Lineprint()
In line 2, we take the input for the number of rows (i.e. the length of the triangle).
In line 5, we create a for
loop to handle the number of rows.
In line 8, we create a nested for
loop (inner loop), to handle the number of columns.
In line 11, we print the pattern (*
). Any other character could be printed by being in the print statement. The end statement helps us to be on the same line till the loop finishes.
In line 14, we use print()
, to move to the next line.