Generate a left-angled triangle using numbers in Python

We can print a plethora of patterns using Python. The only prerequisite to do this is a good understanding of how loops work in Python.

Here, we will be using simple for loops to generate a left-angled triangle using numbers.

Description

A triangle is said to be left-angled if – and only if – it has one angle equal to 90 degrees on its right side.

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

  • Outer loop: To handle the number of rows.
  • Inner loops: One to handle the initial spaces and the other to print the numbers.

Code

Let’s look at the below code snippet.

# 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 numbers
for j in range(i+1):
print(j+1, 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 number 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 left-angled triangle, i.e., the characters are printed from right to left. Unless it is updated, the triangle will be a right-angled triangle.

  • In line 18, we create our second inner nested loop to print the numbers.

  • In line 19, we printed j+1, which results in iteration from 1 (since j + 1) to the length of i in each row. As i keeps increasing with increasing rows, the numbers keep increasing as the line number increases.

Free Resources