Home

 › 

Articles

 › 

Understanding Pattern Program In Python, With Examples

Python Tuples vs Lists

Understanding Pattern Program In Python, With Examples

Key Points

  • Patterns in Python are often used for aesthetic reasons, but can also be used in video game design and mathematical problems.
  • Pyramid patterns, inverted pyramids, diamond patterns, square patterns, and chessboard patterns are some common types of patterns that can be created in Python.
  • Pascal’s triangle is a useful pattern in mathematics that represents binomial coefficients.
  • Understanding how to write pattern programs in Python is educational and can help improve coding logic.

You may think most outputs of coding programs are rather complicated and fairly uninteresting from a visual perspective. However, this isn’t always the case. Creating patterns in Python can lead to some surprising and aesthetically pleasing results. Getting used to the algorithms and steps involved can be very educational in your programming journey, by helping to refine your understanding of programming logic. The variety of patterns you can create is immense. In this article, we’re going to explore some of the most common kinds of patterns you can create in Python, along with some simple examples of how to implement them yourself.

What Are Patterns in Python, and How Are They Created?

When we use the term “pattern”, we usually mean code that produces a visually appealing and recognizable structure. Often, this is a common shape, such as a pyramid, triangle, rectangle, square, diamond, or even chessboard. While these are often used simply for aesthetic reasons, they can be used in various programming projects, such as video game design and mathematical problems.

Most of the time, we use a combination of nested loops (a loop within a loop) and string manipulation to create patterns. Being able to understand how patterns are made in Python will help you make your code more efficient and get to grips with common coding logic. Next, let’s get started with making some patterns!

Pyramid Patterns

For most intents and purposes, triangle and pyramid patterns are equivalent, although there are some special cases of triangles we’ll mention later. But first, let’s examine some various kinds of pyramid patterns.

Pyramid of Numbers

rows = 9
for i in range(1, rows+1):
    print(" " * (rows-i) + (str(i) + " ") * i)

We use a for loop, where i is the row number, to iterate over each row. Spaces are created based on the difference between the total row number and the current row number to enforce the correct shape. We convert the value of i to a string, and add a space after each value, determining the number of values from i.

pyramid of numbers in Python.
A simple example of implementing a pyramid of numbers in Python.

©History-Computer.com

Pyramid of Stars

rows = 9
for i in range(1, rows+1):
    print(" " * (rows-i) + "*" * (2*i – 1))

This uses similar code to before, but we repeat the asterisk character “2 * i – 1” times to create the pattern, rather than incrementing numbers.

pyramid of stars in Python.
Creating a pyramid of stars in Python.

©History-Computer.com

Alphabetic Pyramid

rows = 9
current_char = 65
for i in range(1, rows+1):
    print(" " * (rows-i) + chr(current_char) * (2*i - 1))
    current_char += 1

Here, we use the ASCII code for the initial character, i.e. 65 for A. We have similar code for printing the pyramid pattern but we use the “chr()” function, which returns a string based on the ASCII character in question.

alphabetic pyramid in python.
You can also create an alphabetic pattern using ASCII codes and incrementing by 1.

©History-Computer.com

Hollow Pyramid

rows = 9
for i in range(1, rows+1):
    if i == 1:
        print(" " * (rows-i) + "*")
    elif i == rows:
        print("*" * (2*i - 1))
    else:
        print(" " * (rows-i) + "*" + " " * (2*i - 3) + "*")

We check if the current row is the first row, and if so, we print a singular asterisk to begin the pyramid. We also use an elif statement to check if the current row is equal to the total row number, i.e., to print the last row using a similar formula as before. To print the intermediate rows, we use the else statement. This prints the hollow portion using “’ ‘ * (2*i -3)”, which determines the number of spaces needed as a function of the row number.

hollow pyramid of stars in Python.
Hollow pyramids are an interesting pattern you can create.

©History-Computer.com

Pyramid of Incrementing Numbers

rows = 4
current_num = 1
for i in range(1, rows+1):
    print(" " * (rows-i) + " ".join(str(num) for num in range(current_num, current_num+i)))
    current_num += i

This type of pyramid contains numbers that are incremented by a certain value, in this case, 1. We use “current_num” to keep track of the current number. The sequence of numbers is generated and converted to strings, which are joined together to print consecutive numbers. The current number is incremented by i after each row, to ensure the numbers progress correctly.

incrementing number pyramid in python.
You can increment integer values as well to create fun patterns.

©History-Computer.com

Half Pyramid of Numbers

rows = 9

for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

We use j to represent the columns in a half pyramid. We use a similar loop to iterate over the rows, but we use an additional inner loop to print the j values, which represent the current column. By running the loop from 1 to i + 1, we can print numbers iterating from 1 to i inclusively.

half pyramid of numbers in python.
We must represent the columns to create a half pyramid pattern.

©History-Computer.com

Alphabetic Half Pyramid

rows = 9
current_char = 65

for i in range(1, rows+1):
    print(" " * (rows - i) + chr(current_char) * i)
    current_char += 1

This is similar to the full pyramid but with no “2” modifier.

half alphabetic pyramid in python.
Alphabetic half pyramids are similar in implementation to full pyramids.

©History-Computer.com

Half Pyramid of Stars

rows = 9

for i in range(1, rows + 1):
    print("*" * i)

We use the same for loop as before. The multiplication of * by i ensures that we print the correct number of asterisks in each row.

half pyramid of stars in Python.
Example of a half pyramid of stars in Python.

©History-Computer.com

Half Pyramid of Incrementing Numbers / Floyd’s Triangle

rows = 4
current_num = 1

for i in range(1, rows+1):
    for j in range(i):
        print(current_num, end=" ")
        current_num += 1
    print()

This is a little simpler than the full pyramid version. We use a nested loop structure to control the number of rows and the number of elements within each row. Each value is incremented by 1 and then printed, and a newline character is printed after each completion of the inner loop to move to the next line. We can also refer to this sort of half pyramid as Floyd’s triangle, named after Robert W. Floyd, the computer scientist.

incrementing half pyramid in Python.
Floyd’s triangle is an array often used to study mathematical sequences.

©History-Computer.com

Inverted Pyramids

These patterns essentially have the same code as the ordinary full pyramids, except that we change the arguments of the “range()” function so that the iterations are in reverse order.

Inverted Pyramid of Numbers

rows = 9

for i in range(rows, 0, -1):
    print(" " * (rows - i) + (str(i) + " ") * i)
inverted pyramid of numbers in Python.
We simply reverse the iteration order to construct an inverted pyramid.

©History-Computer.com

Inverted Pyramid of Stars

rows = 9
for i in range(rows, 0, -1):
    print(" " * (rows-i) + "*" * (2*i - 1))
inverted pyramid of stars in Python.
An inverted pyramid of stars in Python.

©History-Computer.com

Alphabetic Inverted Pyramid

rows = 9
current_char = 65

for i in range(rows, 0, -1):
    print(" " * (rows - i) + chr(current_char) * (2*i - 1))
    current_char += 1
Inverted alphabetic pyramid in Python.
Implementing an inverted alphabetic pyramid in Python.

©History-Computer.com

Inverted Pyramid of Incrementing Numbers

rows = 4
current_num = 1

for i in range(rows, 0, -1):
    numbers = [str(num) for num in range(current_num, current_num + i)]
    print(" " * (rows - i) + " ".join(numbers))
    current_num += i
Inverted incrementing pyramid in Python.
Creating an inverted pyramid of incrementing numbers.

©History-Computer.com

Hollow Inverted Pyramid

rows = 9

for i in range(rows, 0, -1):
    if i == 1:
        print(" " * (rows - i) + "*")
    elif i == rows:
        print("*" * (2*i - 1))
    else:
        print(" " * (rows - i) + "*" + " " * (2*i - 3) + "*")
inverted hollow pyramid in Python.
Implementing the inverse of a hollow pyramid is relatively simple.

©History-Computer.com

Inverted Half Pyramids

Again, these are very similar to half pyramids in terms of implementation, but with a reverse order of iterations.

Inverted Half Pyramid of Stars

rows = 9

for i in range(rows, 0, -1):
    print("*" * i)
inverted half pyramid of stars in Python.
Example of an

i

nverted half pyramid of stars in Python.

©History-Computer.com

Inverted Half Pyramid of Numbers

rows = 9

for i in range(rows, 0, -1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()
inverted half pyramid of numbers in Python.
You can create an inverted half pyramid of numbers in Python by slightly modifying the code.

©History-Computer.com

Inverted Half Pyramid of Incrementing Numbers

rows = 4
current_num = 1

for i in range(rows, 0, -1):
    for j in range(i):
        print(current_num, end=" ")
        current_num += 1
    print()
inverted incrementing half pyramid in Python.
This can be thought of as an inverted Floyd’s triangle.

©History-Computer.com

Pascal’s Triangle

This triangle has many uses in mathematics. The values in the triangle represent binomial coefficients, i.e., the number of ways to choose a certain number of items from a set of items. For example, the first row only has 1 in it. This tells us there is one way of choosing zero items from a set of zero items. A clearer example would be the 4th row, which has the coefficients 1, 3, 3, 1. These represent the number of ways we can choose zero, one, two, or three items from a set of three items, respectively.

Note that we can also implement this as a symmetrical triangle. But the values on the left will be identical to the values on the right.

def generate_pascals_triangle(num_rows):
    triangle = []

    for row in range(num_rows):
        current_row = []

        for col in range(row + 1):
            if col == 0 or col == row:
                current_row.append(1)
            else:
                previous_row = triangle[row - 1]
                current_element = previous_row[col - 1] + previous_row[col]
                current_row.append(current_element)

        triangle.append(current_row)

    return triangle


num_rows = 9
pascals_triangle = generate_pascals_triangle(num_rows)

for row in pascals_triangle:
    print(row)

We use the “generate_pascals_triangle()” function here to return the triangle as a list of lists. The “triangle” list is used to store the rows of the triangle. We also use a for loop to iterate over each row. Another list, “current_row”, is then used to store the current row’s elements. We then iterate over each column and use two conditions to input the values. The first checks if the current column is the first or last column, i.e., an edge of the triangle. If so, the value is set to 1. The second condition calculates the current value as the sum of the elements in the previous row in the same column and the next column.

After the loop finishes, the complete triangle is returned. We can specify the desired number of rows in the last code block.

Pascal's triangle in Python.
Pascal’s triangle provides binomial coefficients for expansion and calculating probabilities.

©History-Computer.com

Diamond Patterns

Another interesting pattern in Python is the diamond pattern. Generally, we create these by using a nested loop structure, where we create each half of the diamond in turn. Below are some common kinds of diamond patterns.

Diamond of Stars

rows = 9

for i in range(1, rows + 1):
    print(" " * (rows - i) + "* " * i)

for i in range(rows - 1, 0, -1):
    print(" " * (rows - i) + "* " * i)

Essentially, the first loop prints the top half of the diamond. The second loop prints the bottom half. We use a similar strategy as before (forwards and backwards iterations).

Diamond of stars in Python.
We can create diamonds by using a for loop for each half.

©History-Computer.com

Diamond of Numbers

rows = 9

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

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

Similar logic is used as we did for the diamond of asterisks, and keep track of the columns.

diamond of numbers in Python.
We use similar logic to the diamond of stars and half pyramids to create a diamond of numbers.

©History-Computer.com

Square Patterns

Square patterns are relatively easy to implement because the number of rows and columns is identical. Let’s take a look at some examples of squares.

Square of Stars

size = 9

for i in range(size):
    for j in range(size):
        print("*", end=" ")
    print()

This is quite a simple code block since the parameters for printing the row and column values are identical. You can easily exchange “*” with any other character or symbol as desired.

square of stars in Python.
Squares are quite easy to implement as the rows and columns are identical.

©History-Computer.com

Square of Numbers

rows = 9

for i in range(1, rows + 1):
    for j in range(1, rows + 1):
        print(j, end=" ")
    print()

This is very similar to a pyramid of numbers, except we take the same arguments with both for loops.

square of numbers in Python.
The for loops use the same arguments when we create square patterns.

©History-Computer.com

Square of Incrementing Numbers

size = 9
current_num = 1

for i in range(1, size + 1):
    for j in range(1, size + 1):
        print(current_num, end=" ")
        current_num += 1
    print()

As with other examples, we use a nested loop structure to iterate over the rows and columns. The “current_num” variable keeps track and increments by 1 with each value.

square of incrementing numbers in Python.
When incrementing, we use a variable to keep track of the current number.

©History-Computer.com

Chessboard Pattern

Lastly, we have the chessboard pattern, which can be intriguing to play around with. Here is a fairly simple pattern using asterisks:

size = 9

for row in range(size):
    for col in range(size):

        if (row + col) % 2 == 0:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()

Similarly to the square, we can use nested loops that take the same arguments. We use if and else statements to print the correct value, i.e., a character or a space, on each square of the board in an alternating fashion. If the sum of the row and column indices is evenly divisible, it must be even, and “*” is printed. Otherwise, a blank space is printed. This constructs the chessboard pattern. You can change “*” out for any other character as you wish.

chessboard in Python.
This pattern is an interesting way to visualize a chessboard in Python.

©History-Computer.com

Patterns in Python: Wrapping Up

Understanding how to write pattern programs in Python is not only an intriguing and fun exercise but educational as well. You can familiarize yourself with coding logic by understanding how these programs are implemented, and even use some of them to solve mathematical problems, e.g., Pascal’s triangle. Using for loops and condition statements is an effective way to construct many types of patterns, of which there are essentially endless variations. You can create patterns using special characters or integers, in ascending or descending order. Patterns can even be used in areas such as video game design and data science, so being able to appreciate how they work will help you in your coding journey.

Summary Table

Pattern TypeDescription
Pyramid PatternsPatterns that form a pyramid shape, such as Pyramid of Numbers, Pyramid of Stars, Alphabetic Pyramid, Hollow Pyramid, Pyramid of Incrementing Numbers, Half Pyramid of Numbers, Alphabetic Half Pyramid, Half Pyramid of Stars, Half Pyramid of Incrementing Numbers / Floyd’s Triangle.
Inverted PyramidsPatterns that form an inverted pyramid shape, such as Inverted Pyramid of Numbers, Inverted Pyramid of Stars, Alphabetic Inverted Pyramid, Inverted Pyramid of Incrementing Numbers, Hollow Inverted Pyramid.
Inverted Half PyramidsPatterns that form an inverted half pyramid shape, such as Inverted Half Pyramid of Stars, Inverted Half Pyramid of Numbers, Inverted Half Pyramid of Incrementing Numbers.
Pascal’s TriangleA triangle with many uses in mathematics. The values in the triangle represent binomial coefficients.
Diamond PatternsPatterns that form a diamond shape, such as Diamond of Stars, Diamond of Numbers.
Square PatternsPatterns that form a square shape, such as Square of Stars, Square of Numbers, Square of Incrementing Numbers.
Chessboard PatternA pattern that forms a chessboard using asterisks.

Frequently Asked Questions

What patterns can be created in Python?

The number of patterns that can be created in Python is virtually limitless, but some common ones include variations of pyramids (i.e., full, half, and inverted), squares and rectangles, Pascal’s triangle, Floyd’s triangle, and chessboard patterns. You can create these patterns with integers, either of the same value or incrementing, decrementing, or alternating, or with characters, e.g., hashes, asterisks, or symbols.

What can patterns in Python be used for?

Patterns are often used for educational purposes, to familiarize yourself with coding logic in general, and to get used to creating programs in Python. You can also use them to visualize data, break down problems, and create designs for things such as video games.  Some patterns can be used for mathematical problems and calculating probabilities, such as Pascal’s triangle.

What is Pascal's triangle?

Pascal’s triangle is a triangular sequence where each value is equal to the sum of the two values in the same column and the next column in the previous row. It’s notable because each number represents a binomial coefficient. As such, the sequence can be used to calculate probabilities, expand binomial expressions and for dynamic programming problems.

Can patterns only be created in Python?

No, most programming languages allow you to create various kinds of patterns, but some are associated more commonly with particular languages.

What risks are there with using patterns?

If your code isn’t as efficient as it could be, running pattern programs can be needlessly complex and introduce unnecessary overheads. Without understanding how the algorithms work, you may end up with unsuitable or incorrect code.

To top