Python program to print pyramid number pattern

Python Pattern Printing Program to print pyramid number pattern
Python Pattern Printing Program

Problem Statement

Write a program to print the following number pattern for a given number of rows N.

Input Format

 Integer N (number of rows) 

Output Format

 A symmetric number pattern of N rows 

Examples

Sample Input 1 :

4

Sample Output 1 :


   1
  212
 32123
4321234

Sample Input 2 :

5

Sample Output 2 :


    1
   212
  32123
 4321234
543212345

Solution Approach

The idea is to use nested loops:

  1. Use spaces before numbers to align the pyramid shape.
  2. Print decreasing numbers from i down to 1.
  3. Print increasing numbers from 2 up to i.
  4. Repeat the process for each row until N.

Python Code


N = int(input())

# Outer loop to handle rows
i = 1
while i <= N:
    # Print spaces
    space = 1
    while space <= N - i:
        print(' ', end='')
        space += 1
    
    # Print decreasing numbers
    j = i
    while j >= 1:
        print(j, end='')
        j -= 1
    
    # Print increasing numbers
    j = 2
    while j <= i:
        print(j, end='')
        j += 1
    
    print()  # Move to next line
    i += 1

Try it Online

Previous Post Next Post