Pattern Program in Python

Ayushi Trivedi Last Updated : 11 Jun, 2024
6 min read

Introduction

In this comprehensive guide, we’ll delve into the world of pattern programming using Python, a fundamental exercise for mastering nested loops and output formatting. This article covers a wide array of patterns, including basic star and number patterns, such as right triangles and pyramids, as well as more intricate designs like Pascal’s Triangle, spiral number patterns, and character-based diamonds. Through detailed explanations and Python code examples, you’ll learn to create visually appealing patterns while enhancing your understanding of loops, conditionals, and string manipulations in Python.

Pattern Program in Python

Overview

  • Understand the use of nested loops to create various patterns in Python.
  • Gain proficiency in managing spaces and newlines for output formatting.
  • Learn to implement and visualize common patterns like triangles, pyramids, and diamonds.
  • Develop problem-solving skills by tackling complex patterns such as Pascal’s Triangle and spiral number patterns.
  • Enhance your ability to manipulate strings and numbers for advanced pattern designs.

Printing Star Patterns

Printing star patterns is a foundational exercise in programming, helping to understand nested loops and output formatting. By creating various star designs, you’ll gain practical experience in controlling loops and managing spaces, essential skills for any programmer.

Right Triangle Star Pattern

*
**
***
****
*****

Python Code:

n = 5
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print('*', end=' ')
    print()

Explanation:

  • The outer loop runs from 1 to n (5 in this case) for each row.
  • The inner loop runs from 1 to the current value of the outer loop (i) to print stars.

Inverted Right Triangle Star Pattern

*****
****
***
**
*

Python Code:

n = 5
for i in range(n, 0, -1):
    for j in range(1, i + 1):
        print('*', end=' ')
    print()

Explanation:

  • Outer loop runs from n down to 1 for each row.
  • Inner loop runs from 1 to the current value of the outer loop (i) to print stars.

Pyramid Star Pattern

    *
   ***
  *****
 *******
*********

Python Code:

n = 5
for i in range(1, n + 1):
    print(' ' * (n - i) + '*' * (2 * i - 1))

Explanation:

  • Outer loop runs from 1 to n for each row.
  • print(‘ ‘ * (n – i) + ‘*’ * (2 * i – 1)) prints spaces followed by stars. Spaces decrease and stars increase per row to form the pyramid.

Diamond Star Pattern

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Python Code:

n = 5
for i in range(1, n + 1):
    print(' ' * (n - i) + '*' * (2 * i - 1))
for i in range(n - 1, 0, -1):
    print(' ' * (n - i) + '*' * (2 * i - 1))

Explanation:

  • The first loop creates the upper part of the diamond.
  • The second loop (inverted) creates the lower part of the diamond.

Number Patterns

Number patterns are a great way to practice and understand nested loops and output formatting in programming. These patterns, ranging from simple sequences to complex arrangements, help in enhancing logical thinking and problem-solving skills in Python.

Simple Number Pattern

1
12
123
1234
12345

Python Code:

n = 5
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end=' ')
    print()

Explanation:

  • Outer loop runs from 1 to n.
  • Inner loop prints numbers from 1 to the current value of the outer loop (i).

Number Pyramid Pattern

    1
   2 2
  3 3 3
 4 4 4 4
5 5 5 5 5

Python Code:

n = 5
for i in range(1, n + 1):
    print(' ' * (n - i) + ' '.join(str(i) for _ in range(i)))

Explanation:

  • Outer loop runs from 1 to n.
  • print(‘ ‘ * (n – i) + ‘ ‘.join(str(i) for _ in range(i))) prints spaces followed by the current number (i) repeated i times.

Character Patterns

Character patterns involve creating visual structures using letters and symbols, offering a fun and engaging way to practice nested loops and string manipulation in Python. These patterns range from simple alphabet sequences to intricate designs, enhancing both logical thinking and coding skills.

Alphabet Pyramid Pattern

    A
   B B
  C C C
 D D D D
E E E E E

Python Code:

n = 5
for i in range(1, n + 1):
    print(' ' * (n - i) + ' '.join(chr(64 + i) for _ in range(i)))

Explanation:

  • Outer loop runs from 1 to n.
  • chr(64 + i) converts the number to the corresponding ASCII character (A, B, C, …).

Diamond Character Pattern

    A
   B B
  C C C
 D D D D
E E E E E
 D D D D
  C C C
   B B
    A

Python Code:

n = 5
for i in range(1, n + 1):
    print(' ' * (n - i) + ' '.join(chr(64 + i) for _ in range(i)))
for i in range(n - 1, 0, -1):
    print(' ' * (n - i) + ' '.join(chr(64 + i) for _ in range(i)))

Explanation:

  • The first loop creates the upper part of the diamond.
  • The second loop creates the lower part, similar to the upper part but inverted.

More Advanced Pattern Programs in Python

Let’s explore some more advanced pattern programs that involve additional complexity and logic. These patterns will challenge your understanding of loops, conditionals, and Python’s string manipulation capabilities.

Floyd’s Triangle

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Python Code:

n = 5
num = 1
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(num, end=' ')
        num += 1
    print()

Explanation:

  • Outer loop runs from 1 to n.
  • Inner loop runs from 1 to the current value of the outer loop (i), printing and incrementing the number each time.

Pascal’s Triangle

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Python Code:

def print_pascal_triangle(n):
    for line in range(1, n + 1):
        coef = 1
        for i in range(1, n - line + 1):
            print(" ", end="")
        for i in range(1, line + 1):
            print(coef, end=" ")
            coef = coef * (line - i) // i
        print()

n = 5
print_pascal_triangle(n)

Explanation:

  • Outer loop controls the number of lines.
  • Inner loops manage spaces and coefficients.
  • The coefficient is calculated using the binomial coefficient formula.

Spiral Number Pattern

1  2  3  4  5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

Python Code:

def spiral_print(n):
    mat = [[0] * n for _ in range(n)]
    left, right, top, bottom = 0, n - 1, 0, n - 1
    num = 1
    while left <= right and top <= bottom:
        for i in range(left, right + 1):
            mat[top][i] = num
            num += 1
        top += 1
        for i in range(top, bottom + 1):
            mat[i][right] = num
            num += 1
        right -= 1
        for i in range(right, left - 1, -1):
            mat[bottom][i] = num
            num += 1
        bottom -= 1
        for i in range(bottom, top - 1, -1):
            mat[i][left] = num
            num += 1
        left += 1
    for row in mat:
        print(' '.join(str(x) for x in row))

n = 5
spiral_print(n)

Explanation:

  • The matrix is filled in a spiral order by updating boundaries (left, right, top, bottom) and incrementing the number.

Zigzag Number Pattern

1
3 2
4 5 6
10 9 8 7
11 12 13 14 15

Python Code:

n = 5
num = 1
for i in range(1, n + 1):
    if i % 2 != 0:
        for j in range(1, i + 1):
            print(num, end=' ')
            num += 1
    else:
        start = num + i - 1
        for j in range(i):
            print(start, end=' ')
            start -= 1
            num += 1
    print()

Explanation:

  • Alternates between incrementing and decrementing the number based on the current row being odd or even.

Hourglass Star Pattern

*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********

Python Code:

n = 5
for i in range(n, 0, -1):
    print(' ' * (n - i) + '*' * (2 * i - 1))
for i in range(2, n + 1):
    print(' ' * (n - i) + '*' * (2 * i - 1))

Explanation:

  • First loop creates the upper inverted pyramid.
  • Second loop creates the lower pyramid, starting from 2 to avoid duplicating the middle line.

Conclusion

Learning Python using pattern programs is essential since it helps reinforce concepts such as output formatting, conditionals, and nested loops. These applications provide a wide variety of tasks, ranging from simple forms like pyramids and right triangles to more complex patterns like Pascal’s Triangle and spiral numbers. It is vital practice for every aspiring programmer to learn these patterns because they not only help with coding but also with problem-solving.

Frequently Asked Questions

Q1. What are pattern programs in Python?

A. Pattern programs in Python involve creating visual structures of characters, numbers, or symbols using loops and conditional statements. They are useful for practicing control flow and understanding how to format output in Python.

Q2. Why are pattern programs important for learning Python?

A. Pattern programs help in mastering nested loops, managing spaces and newlines, and developing logical thinking. They provide a solid foundation for more complex programming concepts and enhance problem-solving skills.

Q3. What are some common types of pattern programs?

A. Numerous patterns such as Floyd’s Triangle, star patterns , and character patterns are examples of common pattern programs.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details