×

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used programming language in this decade is the ease with which numerous libraries may be implemented. Although learning is simple, most of interviewers frequently ask us how we built the logic for pattern programmes which is the main key to programming skills.

Pattern programmes in Python are followed as:

  • Square pattern
  • Left triangle alphabet pattern
  • Right triangle pattern
  • Pascals triangle pattern
  • Hollow triangle alphabet pattern
  • Number pyramid pattern
  • Diamond pattern
  • Hourglass pattern

Before learning patterns lets discuss the code which is used to print the numbers from 0-9 and it is followed by for loop.

Code:

for i in range(10):
 print(i, end=’  ’)

Output:

0 1 2 3 4 5 6 7 8 9

Different Patterns are followed as:

Square Pattern:

Generating square pattern is very easy using Python. In order to make a square pattern, we need to utilise two stacked loops. We can set the internal loop to print the number a certain number of times, and it will print that many times. The internal loop will run based on the declaration done in outer loop.

Code:

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

Output:

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

Left Triangle Alphabet Pattern:

A triangle-shaped pattern made out of numbers is called the left triangle pattern. The programme for this will consist of two nested loops, with the inner loop printing the number of times the outer loop has been executed and doing so for each iteration.

Code:

a = 5
for m in range(a+1):
    for n in range(1, m+1):
      print(n, end=' ')
    print()

Output:

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

And we can also edit and manipulate the code that tends a pattern that modifies each succeeding digit in a row, or another pattern that modifies each succeeding digit in a column.

Code:

a = 5
for m in range(a+1):
    for n in range(1, m+1):
      print(m, end=' ')
    print()

Output:

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

Right Angle Pattern:

Every time the pattern is repeated, the number of spaces rises at first.

Two loops are needed and the need is described as the first loop is initiated to

print the spaces and the other loop is declared to print the numbers in the

specified pattern.

Code:

m = 5
for a in range(m):
    for j in range(1, m - a):
        print(" ", end="")
    for h in range(1, a + 2):
        print(h, end='')
    print()

Output:

    1
   12
  123
 1234
12345

Right Pascal Triangle:

Above is a diagram of the right pascal triangle pattern. Once more, it has two figures within it: a left triangle and a reverse left triangle. How to create both of them has been demonstrated above. Let's examine this pattern's whole source code.

Code:

n = 5
# upper triangle formation
for m in range(n):
    for k in range(m + 1):
        print(k+1, end="")
    print()
# lower triangle formation
for m in range(n):
    for k in range(n - m - 1):
        print(k+1, end="")
    print()

Output:

1
12
123
1234
12345
1234
123
12
1

Hollow Triangle Alphabet Pattern:

The voids throughout the pattern make it a little difficult to make. Keep in mind a few things when creating this: only print numbers in the first and last rows, and only print numbers in the first and last positions of other rows, leaving the remainder blank.

Code:

n = 6
for a in range(1, n+1):
    count = 1
    for k in range(a):
        if k == 0 or k == a-1:
            print(count, end='')
            count += 1
        else:
            if a != n:
                print(' ', end='')
            else:
                print(count, end='')
                count += 1
    print()

Output:

1
12
1 2
1  2
1   2
123456

Number Pyramid Pattern:

A well-known pattern that may be made with numbers is the pyramid pattern.

Each line contains an odd number of integers; the first line contains one, the second contains two, the third contains three, and so on. The programme has two internal loops, the first of which prints white space and the second of which prints the growing integers 2n +1

Code:

a = 5
for m in range(a):
    for l in range(a - m - 1):
        print(' ', end='')
    for h in range(2 * m + 1):
        print(h + 1, end='')
    print()

Output:

   1
   123
  12345
 1234567
123456789

Number Pattern:

This diamond pattern has numbers in it. If we look attentively, we will notice two figures in the pattern: a number pyramid and a reverse number pyramid. Therefore, we must write a programme that prints a number pyramid and then reverses the pattern back to front.

Code:

a = 5
#top pyramid
for m in range(a):
    for k in range(a - m - 1):
        print(' ', end='')
    for k in range(2 * m + 1):
        print(k+1, end='')
    print()
#bottom pyramid
for m in range(a - 1):
    for k in range(m + 1):
        print(' ', end='')
    for k in range(2*(a - m - 1) - 1):
        print(k+1, end='')
    print()

Output:

     1
    123
   12345
  1234567
 123456789
  1234567
   12345
    123
     1

Hourglass Pattern:

Another well-known pattern that may be made with numbers is the hourglass pattern. Although it is the same as a diamond pattern, we should have a mental image of how it looks. Two figures can be seen in the pattern when it is observed: one is the number pyramid and the other is the reverse number pyramid. So here is a complete programme for this pattern utilising the ideas from the programme above.

Code:

a = 5   # bottom pyramid
for m in range(a-1):
    for s in range(i):
        print(' ', end='')
    for h in range(2*(a-m)-1):
        print(h+1, end='')
    print()
# top pyramid
for m in range(a):
    for s in range(a-m-1):
        print(' ', end='')
    for h in range(2*m+1):
        print(h+1, end='')
    print()

Output:

123456789
 1234567
  12345
   123
    1
   123
  12345
 1234567
123456789

Related Topics

Python slice()

Python slice() class The slice() class return a slice object representing the set of indices specified by range(start, stop, step).  Syntax class slice(stop)          or class slice(start, stop[, step]) Parameter Start: This parameter represents an integer number specifying at...

1 minute read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Python Generator

Python Generator: A Function is said to be a Python Generator that produces or generates a sequence of results. A Python Generator maintains its native state to work so that...

6 minutes read.

Python Banner

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.