Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print Right Triangle Pattern

Print a growing right triangle of stars with Python nested loops. Students map the outer loop to rows and the inner loop to a row's exact character count.

IntermediatePhase 2 - Level 4: Pattern PrintingExample 1 of 13
print-right-triangle-pattern.py
1# Take n
2n = int(input("Enter number of rows: "))
3
4# Print right triangle
5for i in range(1, n + 1):
6 for j in range(1, i + 1):
7 print("*", end="")
8 print()

Output

Enter number of rows: 5
*
**
***
****
*****

In this one

  • Map loops to rows and columns
  • Grow a row width
  • Place the row newline

How it works

  1. 1

    Visit row widths one through n.

  2. 2

    Print i stars without intermediate newlines.

  3. 3

    End the row before increasing its width.

Edge cases

What does n = 1 print?

What does n = 1 print?

One star on one line.

What does n = 0 print?

What does n = 0 print?

No rows.

What's going on

Row i contains i stars. The outer loop chooses the row number and the inner loop prints that many characters without moving to a new line.

An empty print ends each row after its inner loop finishes. For three rows, the star counts are one, two, and three. Keeping the newline outside the inner loop is what makes a triangle rather than a vertical list.

What does n = 1 print? One star on one line.

What does n = 0 print? No rows.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which loop controls the rows?

Pick an answer to check it.

Question 2

What does n = 1 print?

Pick an answer to check it.

Questions people ask

What does n = 1 print?

One star on one line.

What does n = 0 print?

No rows.

Which loop controls the rows?

The outer loop.