How to generate a left-angled triangle using numbers in Python

Introduction

In this shot, we will discuss how to use numbers to generate a left-angled triangle in Python. We can print a plethora of patterns with Python. The basic and only prerequisite is a good understanding of how loops work in Python.

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

Description

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

Code

We will use 2 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 integers.

# 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. the 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.

  • In line 19, we print j+1, which results in an 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.

  • In line 20, we use print() outside the inner loops and inside the outer loop to move to the next line.

In this way, we can use numbers to generate a left-angled triangle in Python.