How to generate a right-angled triangle using numbers in Python
In this shot, we will discuss how to generate a right-angled triangle using numbers in Python.
We can print a plethora of patterns using Python. The basic and only prerequisite 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 and numbers.
Description
A triangle is said to be right-angled if and only if it has one angle equal to 90 degrees.
To execute this using Python programming, we will be using two for loops:
- An outer loop to handle the number of rows.
- An inner loop to handle the number of columns.
Code
Let’s look at 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(j+1, end=' ')# Next Lineprint()
Explanation
-
In line 2, the input for the number of rows (i.e., length of the triangle) is taken.
-
In line 5, we create a
forloop to handle the number of rows. -
In line 8, we create a nested
forloop (inner loop), to handle the number of columns. -
In line 11, we print the pattern, and we have printed
j+1, which results in iteration from 1 (since j + 1) to length ofiin each row.ikeeps increasing with increasing rows, and so the numbers keep increasing as the line number increases. -
In line 14, we use
print()to move to the next line.