Followers

Showing posts with label Python Programming. Show all posts
Showing posts with label Python Programming. Show all posts

Friday, April 21, 2023

Python Pattern Programming Part-2

 

Various types of python pattern programming using for loop

Pattern 6:

This pattern will print a diamond of numbers with a width equal to the input odd number.

python
n = int(input("Enter the odd number of rows: ")) for i in range(n): if i <= n//2: print(" "*(n//2-i) + "".join(str(j) for j in range(i+1)) + "".join(str(j) for j in range(i, 0, -1))) else: print(" "*(i-n//2) + "".join(str(j) for j in range(n-i, 0, -1)) + "".join(str(j) for j in range(1, n-i+1)))

Output for n = 7:

  1 121 12321 1234321 12321 121 1

Pattern 7:

This pattern will print a spiral of numbers with a size equal to the input number.

python
n = int(input("Enter the size: ")) matrix = [[0 for i in range(n)] for j in range(n)] i, j, di, dj = 0, 0, 0, 1 for k in range(n**2): matrix[i][j] = k+1 if matrix[(i+di)%n][(j+dj)%n]: di, dj = dj, -di i, j = i+di, j+dj for i in range(n): for j in range(n): print(matrix[i][j], end="\t") print()

Output for n = 4:

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

Pattern 8:

This pattern will print a diamond of characters with a width equal to the input uppercase letter.

python
import string letter = input("Enter an uppercase letter: ") n = string.ascii_uppercase.index(letter) + 1 for i in range(n): print(" "*(n-i-1) + string.ascii_uppercase[i] + " "*(2*i-1) + (string.ascii_uppercase[i] if i != 0 else "")) for i in range(n-2, -1, -1): print(" "*(n-i-1) + string.ascii_uppercase[i] + " "*(2*i-1) + (string.ascii_uppercase[i] if i != 0 else ""))

Output for letter = "E":

mathematica
A B B C C D D E E D D C C B B A

Pattern 9:

This pattern will print a right-angled triangle of characters with a height equal to the input uppercase letter.

python
import string letter = input("Enter an uppercase letter: ") n = string.ascii_uppercase.index(letter) + 1 for i in range(n): print(string.ascii_uppercase[i]*(i+1))

Output for letter = "D":

python
A BB CCC DDDD

Pattern 10:

This pattern will print a checkerboard of characters with a size equal to the input number.

python
n = int(input("Enter the size: ")) for i in range(n): for j in range(n): if (i+j)%2 == 0: print("*", end="") else: print(" ", end="") print()

Output for n = 5:

python
* * * * * * * * * * * * *

I hope you find these additional examples helpful!