LearnFrenzy
Sign in Take a free test

Loops · Loops Coding Problems · Question 4

Number pyramid pattern in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Print a centred number pyramid of 5 rows, where row i counts up from 1 to i and back down to 1.

Solution
main.py Run
rows = 5
for i in range(1, rows + 1):
    up = "".join(str(k) for k in range(1, i + 1))
    down = up[-2::-1]                     # the same digits backwards, without the middle one
    print(" " * (rows - i) + up + down)

Output Verified by running it on Python 3

    1
   121
  12321
 1234321
123454321

Each row is leading spaces, the rising digits, and the rising digits reversed minus the last one (up[-2::-1]).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links