Various pattern programming in python using for loop.
Pattern 1:
This pattern will print a triangle of stars with a height equal to the input number.
pythonn = int(input("Enter the number of rows: "))
for i in range(1, n+1):
print("*" * i)
Output for n = 5:
python*
**
***
****
*****
Pattern 2:
This pattern will print a hollow rectangle of stars with a width and height equal to the input numbers.
pythonwidth = int(input("Enter the width: "))
height = int(input("Enter the height: "))
for i in range(height):
if i == 0 or i == height-1:
print("*" * width)
else:
print("*" + " "*(width-2) + "*")
Output for width = 5 and height = 4:
python*****
* *
* *
*****
Pattern 3:
This pattern will print a diamond of stars with a width equal to the input odd number.
pythonn = int(input("Enter the odd number of rows: "))
for i in range(n):
if i <= n//2:
print(" "*(n//2-i) + "*"*(2*i+1))
else:
print(" "*(i-n//2) + "*"*(2*(n-i)-1))
Output for n = 7:
python *
***
*****
*******
*****
***
*
Pattern 4:
This pattern will print a staircase of numbers with a height equal to the input number.
pythonn = int(input("Enter the number of rows: "))
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end="")
print()
Output for n = 5:
python1
12
123
1234
12345
Pattern 5:
This pattern will print a pyramid of numbers with a height equal to the input number.
pythonn = int(input("Enter the number of rows: "))
for i in range(1, n+1):
print(" "*(n-i), end="")
for j in range(1, i+1):
print(j, end="")
for k in range(i-1, 0, -1):
print(k, end="")
print()
Output for n = 5:
python 1
121
12321
1234321
123454321
I hope you find these examples helpful!
No comments:
Post a Comment