## 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 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.

### 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.

### 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.

### 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.

### 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.

### 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 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 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.

## 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 Stars

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

### 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 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
```

### 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 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 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 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()
```

## 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 4^{th} 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.

## 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 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.

## 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 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 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.

## 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.

## 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 Type | Description |
---|---|

Pyramid Patterns | Patterns 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 Pyramids | Patterns 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 Pyramids | Patterns 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 Triangle | A triangle with many uses in mathematics. The values in the triangle represent binomial coefficients. |

Diamond Patterns | Patterns that form a diamond shape, such as Diamond of Stars, Diamond of Numbers. |

Square Patterns | Patterns that form a square shape, such as Square of Stars, Square of Numbers, Square of Incrementing Numbers. |

Chessboard Pattern | A pattern that forms a chessboard using asterisks. |

The image featured at the top of this post is ©DANIEL CONSTANTE/Shutterstock.com.