Write a python program to print right angle triangle pattern using *

1. Introduction

This blog post will illustrate how to create a Python program to print a right-angle triangle pattern using the asterisk symbol (*). This exercise is an excellent way to learn about nested loops in Python, which are a fundamental aspect of creating various patterns and designs in programming.

2. Program Steps

1. Determine the height of the triangle.

2. Use nested loops to print the pattern:

- The outer loop to handle the number of rows.

- The inner loop to handle the number of columns in each row.

3. Code Program

def print_triangle(height):
    # Step 2: Outer loop for each row
    for row in range(1, height + 1):
        # Inner loop for printing '*' in each row
        for column in range(row):
            print('*', end='')
        # Print a new line after each row
        print()

# Step 1: Define the height of the triangle
triangle_height = 5
print_triangle(triangle_height)

Output:

For a triangle height of 5, the output will be:
*
**
***
****
*****

Explanation:

1. The function print_triangle takes an argument height which determines the number of rows in the triangle.

2. The outer for loop (for row in range(1, height + 1)) iterates over each row. The range is set from 1 to height + 1 to include the height number in the loop.

3. The inner for loop (for column in range(row)) handles the number of * to be printed in each row. It iterates as many times as the current row number.

4. After the inner loop completes for a row, print() is used to move to the next line, starting a new row of the pattern.

This program is a straightforward example of using nested loops to create a pattern, in this case, a right-angle triangle using asterisks.


Comments