top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Pattern Program in Python

Introduction

Python is a popular high-level programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. It is widely used in web development, data analysis, machine learning, and more. In the Python programming language, we can create patterns by utilizing For Loops. Here, we can modify them for loops and then print the statement to create a unique Pattern Program in Python, such as stars, numbers, and characters. 

Overview

Python pattern programs involve creating visually appealing shapes or arrangements using various symbols, such as numbers, letters, or asterisks. These patterns can be simple or complex. Below are a wide range of pattern programs, including pyramid, reverse, diamond, number, and alphabet patterns. Each pattern has a unique code implementation. By the end of this guide, you will have a solid foundation in Pattern Program in Python and will be able to create stunning patterns using Python.

Main Features of Python

Python, a widely acclaimed high-level programming language, is distinguished by core features that facilitate developers across various domains. 

1. Simple and Readable Syntax: Python boasts a clean and intuitive syntax, fostering code that is both beginner-friendly and easy to maintain. For instance:

# Python code to print "Hello, World!"
print("Hello, World!")

2. High-Level Language: Python is a high-level language that abstracts complex low-level operations, which makes it exceptionally user-friendly.

3. Cross-Platform Compatibility: Python's cross-platform compatibility allows code written on one operating system to run seamlessly on others.

4. Extensive Standard Library: Python offers a robust standard library replete with pre-built modules for a multitude of tasks, reducing the need for coding from scratch. 

# Example: Getting the current date and time

import datetime
current_time = datetime.datetime.now()
print(current_time)
  1. Vibrant Community Support: Python's vibrant and engaged community of developers continually contributes to open-source libraries and assists in forums and documentation.

  2. Object-Oriented Programming (OOP): Python seamlessly accommodates object-oriented programming, ideal for crafting well-structured, complex applications.

  3. Expansive Third-Party Libraries: Python's extensive ecosystem has third-party libraries and frameworks such as NumPy, pandas, TensorFlow, and Django, which augment its capabilities across diverse domains.

# Example: Using NumPy for array operations,

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr)
print(f"Mean: {mean}")

How to Print Patterns in Python?

Pattern printing in Python is a common programming exercise that helps develop logical and coding skills. In Python, you can achieve this using loops and control structures. 

General Steps to Print Patterns in Python:

  1. Determine the Pattern: Decide on the type of Pattern Program in Python you want to print, such as pyramids, stars, numbers, or letters.

  2. Identify the Pattern Rules: Analyze the pattern to determine the rules governing its structure. This includes the number of rows, the characters to be printed, and their positions.

  3. Use Nested Loops: you'll use nested loops to control the row and column positions within the Python pattern programs. The outer loop manages the rows, and the inner loop handles the columns.

  4. Apply Conditional Statements: In some cases, conditional statements (e.g., if statements) can be used to decide whether to print a character or whitespace at a particular position.

  5. Print the Pattern: Use the print function to display the characters or spaces within the nested loops.

Now, let's explore examples of different patterns in Python.

Print Pyramid, Star, and Diamond patterns in Python

Pattern 1: Simple Pyramid Pattern 

This pattern consists of a pyramid of stars.

Code

n = int(input("Enter the number of rows: "))

for i in range(0, n):
    for j in range(0, i 1):
        print("* ", end="")
    print()

Output

Enter the number of rows: 5
* 
* * 
* * * 
* * * * 
* * * * *

Explanation:

We created a basic pyramid design using the star symbol in the above code. We used int() to ask the user how many rows there were. Then, we use for loop and range() twice to iterate through every single line until we reach the number of rows specified by the user, which is five.

Pattern 2: Reverse Right Angle Pyramid 

This pattern is a reversed right-angle pyramid of stars.

Code

rows = int(input("Enter the number of rows: "))
k = 2 * rows - 2

for i in range(0, rows):
    for j in range(0, k):
        print(end=" ")
    k = k - 2
    for j in range(0, i 1):
        print("* ", end="")
    print()

Output for Pattern 2 with rows = 5:

Enter the number of rows: 5
      * 
     * * 
    * * * 
   * * * * 
  * * * * *

Explanation: In this code, we use two nested loops. The outer loop iterates over the rows in reverse order, starting from n and decrementing by 1 in each iteration. The inner loop prints the symbols (asterisks) in each row determined by the value of the loop variable i. 

Pattern 3: Printing Downward Half-Pyramid 

This Python pattern program is a downward half-pyramid of stars.

# Example: Printing downward half-pyramid

rows = int(input("Enter the number of rows: "))


for i in range(rows 1, 0, -1):
    for j in range(0, i - 1):
        print("*", end=' ')
    print()

Output for Pattern 3 with rows = 5:

Enter the number of rows: 5
* * * * * 
* * * * 
* * * 
* * 
*

Explanation: In this pattern, the outer loop (controlled by variable i) iterates in reverse from n down to 1, representing the rows. The inner loop (controlled by variable j) iterates from 0 to i, printing numbers from 1 to i in each row. It creates an inverted pyramid pattern with decreasing rows and ascending numbers. 

Pattern 4: Printing Triangle Pyramid 

This pattern printing in Python is a triangle pyramid of stars.

# Example: Printing triangle pyramid

n = int(input("Enter the number of rows: "))
m = (2 * n) - 2

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

Output for Pattern 4 with n = 5:

Enter the number of rows: 5
         * 
        * * 
       * * * 
      * * * * 
     * * * * * 

Explanation: In this pattern, we use two nested loops. The outer loop (controlled by variable i) iterates from 0 to n-1, representing the rows. The inner loop (controlled by variable j) iterates from 0 to i, printing the same number n in each row. It creates an inverted pyramid, with each row containing the same number. 

Pattern 5: Downward Triangle Pattern 

This pattern question in Python is a downward triangle pattern of stars.

# Example: Downward triangle pattern

rows = int(input("Enter the number of rows: "))
k = 2 * rows - 2

for i in range(rows, -1, -1):
    for j in range(k, 0, -1):
        print(end=" ")
    k = k 1
    for j in range(0, i 1):
        print("*", end=" ")
    print()

Output for Pattern 5 with rows = 5:

Enter the number of rows: 5
* * * * * * * * * * * 
 * * * * * * * * * * 
  * * * * * * * * * 
   * * * * * * * * 
    * * * * * * * 
     * * * * * * 
      * * * * * 
       * * * * 
        * * * 
         * * 
          * 

Explanation: In this code, we use three nested loops. The outer loop iterates over the rows, the first inner loop prints the spaces before the symbols, and the second inner loop prints the symbols (asterisks) in each row. 

Pattern 6: Diamond Shaped Pattern 

This pattern question in Python is a diamond-shaped pattern of stars.

# Example: Diamond-shaped pattern

rows = int(input("Enter the number of rows: "))
k = 2 * rows - 2


for i in range(0, rows):
    for j in range(0, k):
        print(end=" ")
    k = k - 1
    for j in range(0, i 1):
        print("* ", end="")
    print()


k = rows - 2


for i in range(rows, -1, -1):
    for j in range(k, 0, -1):
        print(end=" ")
    k = k 1
    for j in range(0, i 1):
        print("* ", end="")
    print()

Output for Pattern 6 with rows = 8: 

Enter the number of rows: 8
              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * * 
      * * * * * * * * * 
       * * * * * * * * 
        * * * * * * * 
         * * * * * * 
          * * * * * 
           * * * * 
            * * * 
             * * 
              * 

Explanation: In this code, we use four nested loops. The first two loops are used to print the upper half of the diamond, and the last two loops are used to print the lower half of the diamond. The number of spaces and symbols in each row is determined by the loop variables value. 

Pattern 7: Print Two Pyramids in a Single Pattern

This pattern questions in Python prints two pyramids side by side.

Code:

rows = int(input("Enter the number of rows: "))

for i in range(0, rows):
    for j in range(0, i 1):
        print("*", end=' ')
    print()

for i in range(rows 1, 0, -1):
    for j in range(0, i - 1):
        print("*", end=' ')
    print()

Output for Pattern 7 with rows = 7:

Enter the number of rows: 7
*  
* *  
* * *  
* * * *  
* * * * *  
* * * * * *  
* * * * * * *  
* * * * * * *  
* * * * * *  
* * * * *  
* * * *  
* * *  
* *  
*

Explanation:

The user is prompted to enter the number of rows (rows), which is set to 7 in this example. Two parts of the pattern are printed: the upper pyramid and the lower pyramid, each with its own nested loop structure. In the upper pyramid, the first loop iterates from 0 to row 1; in the lower pyramid, it iterates from rows 1 to 0. Inner loops in both parts print the stars (*) for each row, and spaces are used to separate the stars. The end=' ' argument in the print() function is for spaces after each star. After pattern printing in Python stars for each row in both parts, a new line is added to move to the next row.

Pattern 8: Hourglass Pattern

This is a pattern program in Python to print the Hourglass pattern

Code

rows = int(input("Enter the number of rows: "))
k = rows - 2


for i in range(rows, -1, -1):
    for j in range(k, 0, -1):
        print(end=" ")
    k = k 1
    for j in range(0, i 1):
        print("* ", end="")
    print()


k = 2 * rows - 2


for i in range(0, rows 1):
    for j in range(0, k):
        print(end=" ")
    k = k - 1
    for j in range(0, i 1):
        print("* ", end="")
    print()

Output for Pattern 8 with rows = 5:

Enter the number of rows: 5
   * * * * * * 
    * * * * * 
     * * * * 
      * * * 
       * * 
        * 
        * 
       * * 
      * * * 
     * * * * 
   * * * * * 
  * * * * * *

Explanation:

The user is prompted to enter the number of rows (rows), which is set to 5 in this example. Two parts of the hourglass print pattern in Python are the upper part and the lower part, each with its own nested loop structure. The end=' ' argument in the print() function ensures that spaces are printed after each star. After printing stars for each row in both parts, a new line is added to move to the next row.

Number Pattern in Python

Apart from printing patterns in Python with asterisks or other symbols, you can also print patterns using numbers. Number patterns are a great way to enhance your understanding of loops and conditional statements in Python. Let's explore some interesting number patterns that you can print using Python.

Pattern 1: Number Pattern

The print pattern in Python numbers is a simple and commonly used pattern that involves printing a series of numbers in a specific order. The numbers can be printed in a pyramid-like structure, a straight line, or any other desired shape.

Code:

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

Output:

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

Explanation: To create a Number Pattern, we represented each row with a number, i.e., the first row is number 1, the second row is number 2, the third row is number 3, and so on until row 5.

Pattern 2: Half Pyramid Pattern with Numbers

The half pyramid pattern problems in Python with numbers are similar to the simple number pattern, but it only prints the upper half of the pyramid.

Code:

n = 5
for i in range(n):
    for j in range(n-i):
        print(j 1, end=" ")
    print()

Output:

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

Explanation: To construct a Half pyramid pattern with numbers, we have assigned a number to each row, i.e., the first row is number 1, the second row is numbers 1 and 2, the third row is numbers 1, 2, and 3, and so on until 5.

Pattern 3: Inverted Pyramid Pattern

The inverted pyramid pattern involves printing patterns in Python numbers in an inverted pyramid shape. The number of numbers in each row decreases from top to bottom, and the numbers are printed in descending order.

Code:

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

Output:

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

Explanation: In this code, we use two nested loops as well. The outer loop iterates over the rows in reverse order, starting from n and decrementing by 1 in each iteration. With each row, the number decreases by one, and the row ends at 1. 

Pattern 4: Same Number Inverted Pyramid

The same number inverted pyramid pattern is similar to the inverted pyramid pattern problems in Python, but it prints the same number in each row. The number of numbers in each row decreases from top to bottom.

Code:

n = 5
number = n
for i in range(n):
    for j in range(i 1):
        print(number, end=" ")
    print()

Output:

5 
5 5 
5 5 5 
5 5 5 5 
5 5 5 5 5

Explanation: In this code, we use two nested loops. The outer loop iterates over the rows, and the inner loop prints the same number in each row. The number of numbers in each row increases from left to right, starting from n.

Pattern 5: Descending Order of Numbers

The descending order pattern involves printing numbers in descending order, starting from a given number and decreasing by 1 in each row.

Code:

s = int(input("Please enter the number of rows :"))  
for i in range(s, 0, -1):  
    t = i  
   for j in range(0, i):  
       print(i, end=' ')  
    print(" ")  

Output:

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

Explanation: In this code, we use two nested loops as well. The outer loop iterates over the rows, and the inner loop prints the numbers in descending order. 

Pattern 6: Print 1 to 10 numbers in Pattern

The printing patterns in Python numbers from 1 to 10 involve printing the numbers in a specific pattern, creating a visually appealing arrangement.

Code:

n = 10
for i in range(1, n 1):
    for j in range(1, i 1):
        print(j, end=" ")
    print()

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10

Explanation: In this code, we use two nested loops. The outer loop iterates over the rows, and the inner loop prints the numbers in ascending order. The number of numbers in each row increases from left to right, starting from 1.

Pattern 7: Reverse Pattern from 10 to 1

The reverse pattern program in Python from 10 to 1 involves printing the numbers from 10 to 1 in a specific pattern, creating a visually appealing arrangement.

Code:

n = 10
for i in range(n, 0, -1):
    for j in range(1, i 1):
        print(j, end=" ")
    print()

Output:

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1

Explanation: In this code, we use two nested loops. The outer loop iterates over the rows in reverse order, starting from n and decrementing by 1 in each iteration. The inner loop prints the numbers in ascending order.

Pattern 8: Print Odd Numbers

The pattern problems in Python for printing odd numbers involve printing odd numbers in a specific pattern, creating a visually appealing arrangement.

Code:

rows = int(input("Enter the number of rows: "))
i = 1
while i <= rows:
    j = 1
    while j <= i:
        print((i * 2 - 1), end=" ")
        j = j 1
    i = i 1
    print()

Output:

Enter the number of rows: 5

1 
3 3 
5 5 5 
7 7 7 7 
9 9 9 9 9

Explanation: In this code, we use two nested loops. The outer loop iterates over the rows, and the inner loop prints the numbers in a specific pattern. The number of numbers in each row increases according to the loop variable i.

Pattern 9: Square Pattern using Numbers

Print a square pattern program in Python of numbers where the row number is printed if it is less than or equal to the column number; otherwise, the column number is printed.

Code:

rows = int(input("Enter the number of rows: "))
for i in range(1, rows 1):
    for j in range(1, rows 1):
        if j <= i:
            print(i, end=' ')
        else:
            print(j, end=' ')
    print()

Output:

Enter the number of rows: 5

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

Explanation: The code takes the number of rows as input and prints a square pattern of numbers. If the column number is less than or equal to the row number, it prints the row number; otherwise, it prints the column number.

Pattern 10: Multiplication Number in Column

Print a pattern of numbers where each element is the multiplication of its row and column numbers.

Code

rows = int(input("Enter the number of rows: "))
for i in range(1, rows):
    for j in range(1, i 1):
        print(i * j, end='  ')
    print()

Output

Enter the number of rows: 8

1  
2  4  
3  6  9  
4  8  12  16  
5  10  15  20  25  
6  12  18  24  30  36  
7  14  21  28  35  42  49

Explanation: The code takes the number of rows as input and prints a pattern of numbers where each element is the multiplication of its row and column numbers. It forms a multiplication table-like pattern.

Conclusion

Creating diverse patterns in Python involves the skillful application of nested loops and understanding spacing and character manipulation. For a simple pyramid Pattern Program in Python, the arrangement is achieved through loops, and space management is key to shaping the pattern. Number patterns rely on nested loops to control the spacing between numbers, with the count of numbers aligning with the row number. Alphabet and letter patterns utilize ASCII values, using nested loops to iterate through rows and convert ASCII values into letters, resulting in intricate designs.  

FAQs

Q1: What are custom patterns in Python, and how are they created?

A1: Custom patterns in Python are visual arrangements of characters, numbers, or symbols. They are created using nested loops, where the outer loop controls the number of rows, and the inner loop manages the columns, determining the placement of elements within the pattern.

Q2: Why are nested loops crucial for creating custom patterns in Python?

A2: Nested loops are essential because they provide precise control over the position and arrangement of elements in custom patterns. The outer loop manages rows, while the inner loop handles columns, allowing for complex patterns to be constructed systematically.

Q3: What is the significance of specific conditions in printing hollow pyramid patterns?

A3: Specific conditions, often based on row and column positions, are used in hollow pyramid patterns to control when to print spaces and characters. These conditions ensure the accurate rendering of the desired pattern shape.

Leave a Reply

Your email address will not be published. Required fields are marked *