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

Print Pyramid Pattern

Center a solid star pyramid with Python loops. Students calculate leading spaces and odd star counts, then trace the separate newline that completes each row.

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

Output

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

In this one

  • Compute indentation
  • Use odd star counts
  • Center rows with two loops

How it works

  1. 1

    Print n - i leading spaces.

  2. 2

    Print 2 * i - 1 stars.

  3. 3

    End the row and advance i.

Edge cases

What happens for n = 1?

What happens for n = 1?

There are no leading spaces and one star.

What happens for n = 0?

What happens for n = 0?

No rows print.

What's going on

Row i starts with n - i spaces and then contains 2 * i - 1 stars. As the row grows, indentation shrinks.

For n equal to three, the rows have two, one, zero leading spaces and one, three, five stars. Both inner loops suppress newlines; the final empty print ends the row. Alignment is easiest to inspect in a fixed-width font.

What happens for n = 1? There are no leading spaces and one star.

What happens for n = 0? No rows print.

Quiz

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

Question 1

Why are star counts odd?

Pick an answer to check it.

Question 2

What happens for n = 1?

Pick an answer to check it.

Questions people ask

What happens for n = 1?

There are no leading spaces and one star.

What happens for n = 0?

No rows print.

Why are star counts odd?

The formula is 2 * i - 1.