Printing special pattern in Python

By | December 13, 2022

We have to print the pattern as given in the example below :

Examples:

Input : 4 
Output :
1      1
12    21
123  321
12344321
123  321
12    21
1      1


Input : 5 
Output :
1        1
12      21
123    321
1234  4321
1234554321
1234  4321
123    321
12      21
1        1

Approach :

You can use nested for loop to print such patterns in Python. You can do these with outer and inner for loops. Most of the patterns use the following concepts.

  1. Outer loop to print the number of rows.
  2. Inner loop to print the number of columns.
  3. Variable to print whitespace as required.

Implementation in Python :

def special_pattern ( n ) :
    p = 2 * n

    # loop for no of lines in the pattern
    for i in range ( 1, n ) :
        
        # loop for printing nos from 1 to p
        for j in range ( 1, i + 1 ) :
            print ( j, end = "" )

        # loop for printing spaces between two series
        for k in range ( 1, p-1 ) :
            print ( " ", end = "" )

        # loop for printing reverse nos from p to 1
        for k in range ( i, 0, -1 ) :
            print ( k, end = "" )

        # change in line and updation of variables
        print ( )
        p = p - 2
    p = n
    d = 1

    # loop for no of lines in the pattern
    for i in range ( 1, n + 1 ) :
        
        # loop for printing nos from 1 to p
        for j in range ( 1, p + 1 ) :
            print ( j, end = "" )

        # loop for printing spaces between two series
        for k in range ( 1, d ) :
            print ( " ", end = "" )

        # loop for printing reverse nos from p to 1
        for k in range ( p, 0, -1 ) :
            print ( k, end = "" )

        # change in line and updation of variables
        print ( )
        p = p - 1
        d = d + 2


n = 4
special_pattern ( n )

Output:

1      1
12    21
123  321
12344321
123  321
12    21
1      1 

Please write comments below if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.