Python Pattern Programs using While Loop

In this tutorial, we will learn how to print patterns to console using Python While Loop.

Python Patterns using While Loop

Example 1 – Python Program to Print Right Triangle using While Loop

In this example, we will write a Python program to print the following start pattern to console. We shall read the number of rows and print starts as shown below.

Pattern

For an input number of 4, following would be the pattern.

*
* *
* * *
* * * *

Python Program

</>
Copy
n = int(input('Enter number of rows : '))

i = 1
while i <= n :
    j = 1
    while j <= i:
        print("*", end = " ")
        j += 1
    print()
    i += 1

Inner while loop prints a single row after its complete execution. Outer while loop helps to print n number of rows.

In other words, outer while loop prints the rows, while inner while loop prints columns in each row.

Output

Enter number of rows : 6
*
* *
* * *
* * * *
* * * * *
* * * * * *

Example 2 – Python Program to Print Inverted Right Triangle using While Loop

In this example, we will write a Python program to print the following start pattern to console.

Pattern

For an input number of 4, following would be the pattern.

* * * *
* * *
* *
*

Python Program

</>
Copy
n = int(input('Enter number of rows : '))

i = 1
while i <= n :
    j = n
    while j >= i:
        print("*", end = " ")
        j -= 1
    print()
    i += 1

Output

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

Example 3 – Python Program to Print Number Pattern using While Loop

In this example, we will write a Python program to print the following pattern to console. We shall read the number of rows and print numbers as shown below.

Pattern

For an input number of 5, following would be the pattern.

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

Python Program

</>
Copy
n = int(input('Enter number of rows : '))

k = 1
i = 1
while i <= n :
    j = 1
    while j <= i:
        print("{:3d}".format(k), end = " ")
        j += 1
        k += 1
    print()
    i += 1

Output

Enter number of rows : 7
  1
  2   3
  4   5   6
  7   8   9  10
 11  12  13  14  15
 16  17  18  19  20  21
 22  23  24  25  26  27  28

Conclusion

In this Python Tutorial, we learned to write Python programs to print different types of patterns using While Loop.