Pattern programs in python
Pattern programs in python
Patterns can be printed in python using simple for loops. The outer loop is used for handling the number of rows and the inner loop handles the number of columns.
Here are few patterns and the python program to print the pattern.
Pattern 1 :
Given a number, a simple pyramid pattern with n number of rows is created with the values as column number.
For n = 4, the following number pattern will be printed.
1
1 2
1 2 3
1 2 3 4
Code :
n = int(input("Enter a number : "))
for i in range(n+1):
for j in range(1, i+1):
print(j, end = " ")
print()
Sample input :
n = 5
Sample output :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Output screenshot :
Pattern 2 :
For n =4, the following pattern will be printed.
1 2 3 4
1 2 3
1 2
1
Code :
n = int(input("Enter a number : "))
for i in range(n, 0, -1):
for j in range(1, i+1):
print(j, end = " ")
print()
Sample input :
n = 5
Sample output :
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Output screenshot :
Pattern 3 :
For n = 4,
4 4 4 4
3 3 3
2 2
1
Code :
n = int(input("Enter a number : "))
for i in range(n, 0, -1):
for j in range(1, i+1):
print(i, end = " ")
print()
Sample input :
n = 5
Sample output :
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
Output screenshot :
Pattern 4 :
For n=4,
4
3 3
2 2 2
1 1 1 1
Code :
n = int(input("Enter a number : "))
for i in range(n, 0, -1):
for j in range(i, n+1):
print(i, end = " ")
print()
Sample input :
n = 5
Sample output :
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1
Output screenshot :
For given n , a square pattern is printed with n number of rows.
For n = 4,
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
Code :
n = int(input("Enter a number : "))
for i in range(1, n+1):
for j in range(n):
print(i, end = " ")
print()
Sample input :
n = 5
Sample output :
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Output screenshot :
Pattern 6 :
For n = 4, the following star pattern will be printed.
*
* *
* * *
* * * *
Code :
n = int(input("Enter the number : "))
k = (2*n) - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 2
for m in range(0, i+1):
print("* ", end="")
print()
Sample input :
n = 5
Sample output :
*
* *
* * *
* * * *
* * * * *
Output screenshot :
Comments
Post a Comment