You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – Nested Loops

A loop may also contain another loop within its body. This form of a loop inside another loop is called a nested loop. In a nested loop construction, the inner loop must terminate before the ending of the outer loop.

Example 36.
Program to print pyramid of stars using for loop.
*
* *
* * *
* * * *
* * * * *

# Nested for loop
n = int(input(“Enter a number to form pyramid :”))
for i in range(l,n):
for j in range(l,i):
print(“*”,end =” “)
print( )

Example37.
Program to print inverted triangle of stars using for loop.
* * * * *
* * * *
* * *
* *
*

# Print the pattern
for a in range(5, 0, -1):
for b in range(1,a+1):
print(“*”, end=’ ‘)
print(” “)

Example 38.
Program to print patterns of stars.
* * * * *
* * * * *
* * * * *

# Print the pattern
for a in range(1, 4):
for b in range(1,6):
print(“*”, end=’ ‘)
print(” “)

Let’s Try

Write a program to print the following pattern:

* * *

* * *

* * *

*

* **

*****

*

**

***

Example 39.
Program to print pattern of numbers.
12345
12345
12345

# Print the pattern
for a in ranged, 4):
for b in range(1,6):
print(b, end=’ ‘)
print(” “)

Example 40.
Program to print pattern of numbers.

11111
22222
33333

# Print the pattern
for a in range (1, 4) :
for b in range(1,6) :
print(a, end=’ ‘)
print(” “)

Example 41.
Program to print pattern of numbers.
1
12
123
1234

# Print the pattern
for a in range(1, 5):
for b in range(l,a+l):
print(b, end=’ ‘)
print(” “)

Example 42.
Program to print pattern of numbers.
1
22
333
4444

# Print the pattern
for a in range ( 1, 5):
for b in range(1,a+1):
print(a, end=’ ‘)
print(” “)

Example 43.
Program to print pattern of numbers.
55555
4444
333
22
1

# Print the pattern for a in range(5, 0, -1) :
for b in range(1,a+1):
print(a, end=’ ‘)
print(” “)

Let’s Try

What is the output of following code fragments?

# Print the pattern
for a in range(5, 0, -1):
for b in range(1,a+1):
print(b, end=’ ‘)
print(” “)
# Print the pattern
for a in range(0, 5):
for b in range(1,a+1):
print(“*”, end=’ ‘)
print(” “)

Leave a Reply

Your email address will not be published. Required fields are marked *