0% found this document useful (0 votes)
6 views5 pages

Python Patterns

Uploaded by

Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Python Patterns

Uploaded by

Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Python: Printing Patterns Using Loops

Example 1: – ​Print a number pattern using a for loop and range function.

for num in range(10):


for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n")

Output:

1
22
333
4444
55555
666666
7777777
88888888
999999999

Number Pattern Example 2​:​ Triangular half pyramid number pattern

lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("")

Output:

1
12
123
1234
12345
Print Pyramid and Asterisk pattern in Python

Example 1: ​Program to print Full Triangle Pyramid pattern using an


asterisk (star)

n=7

# number of spaces
k = n - 1

# outer loop to handle number of rows


for i in range(0, n):

# inner loop to handle number spaces


# values changing acc. to requirement
for j in range(0, k):
print(end=" ")

# decrementing k after each loop


k = k - 1

# inner loop to handle number of columns


# values changing acc. to outer loop
for j in range(0, i+1):

# printing stars
print("* ", end="")

# ending line after each row


print("\r")

Output:
Example 2: ​Program to print half pyramid pattern using an asterisk (star)

rows = input("Enter number of rows ")


rows = int (rows)

for i in range (0, rows):


for j in range(0, i + 1):
print("*", end=' ')

print("\r")

Output:
Enter number of rows 4
*
**
***
****

Example 3: ​Print Asterisk (Star) pattern

rows = input("Enter max star to be display on single line")


rows = int (rows)
for i in range (0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")

for i in range (rows, 0, -1):


for j in range(0, i -1):
print("*", end=' ')
print("\r")

Output:

Enter max star to be display on single line 4


*
**
***
****
***
**
*

Example 4:​ Program to print inverted half pyramid using an asterisk (star)

rows = input("Enter number of rows ")


rows = int (rows)

for i in range (rows,0,-1):


for j in range(0, i ):
print("*", end=' ')

print("\n")

Output:
Enter number of rows 4
****

***

**

Example 5: ​Another triangular pattern

k = 8
for i in range(0, 5):
for j in range(0, k):
print(end=" ")
k = k - 2
for j in range(0, i+1):
print("* ", end="")
print(‘\n’)
Output:

You might also like