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

Mirrored Number Pyramid

Create a mirrored number pyramid with Python loops. Students print ascending then descending digits, avoid repeating the center, and account for leading spaces.

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

Output

Enter number of rows: 4
   1
  121
 12321
1234321

In this one

  • Mirror number order
  • Print one peak value
  • Indent before numeric content

How it works

  1. 1

    Print n - i leading spaces.

  2. 2

    Print ascending values one through i.

  3. 3

    Descend from i - 1 to one and end the row.

Walk through Mirrored Number Pyramid

n = 3, row i = 3

  1. 1.n - i is zero, so this row has no leading spaces.
  2. 2.The ascending loop prints 123.
  3. 3.The descending loop prints 21; together the row is 12321.

Edge cases

What is the second numeric row?

What is the second numeric row?

121.

What does n = 1 print?

What does n = 1 print?

One row containing 1.

What's going on

This pyramid climbs from one to the row number, then descends back to one. The two number loops create a mirrored row rather than a simple counting triangle.

The descending loop begins at i - 1 so the peak is printed once. Row three is 12321, preceded by n - 3 spaces. Values are printed without separators, unlike the later spaced ascending pyramid. Multi-digit values alter the visual alignment.

What is the second numeric row? 121.

What does n = 1 print? One row containing 1.

Quiz

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

Question 1

Why does descent start at i - 1?

Pick an answer to check it.

Question 2

What is the second numeric row?

Pick an answer to check it.

Questions people ask

What is the second numeric row?

121.

What does n = 1 print?

One row containing 1.

Why does descent start at i - 1?

The peak value has already printed.