§ One
loop inside another loop is called a Nested Loop.
§ Any
number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops. The nesting level can be defined
at n times.
for i in
range(1,5):
#codes inside the body of
outer loop
for j in
range(1,5):
#codes inside the body of
both outer and inner loop
#codes inside the body of
outer loop
n=int(input('enter number'))
#outer loop
for i in range(1,n+1):
print("Outer
loop iteration " , i);
#inner
loop
for j in
range(1,5):
print("i=
",i," j=",j)
enter number 5
Outer loop
iteration 1
i= 1 j= 1
i= 1 j= 2
i= 1 j= 3
i= 1 j= 4
i= 1 j= 5
=================
Outer loop
iteration 2
i= 2 j= 1
i= 2 j= 2
i= 2 j= 3
i= 2 j= 4
i= 2 j= 5
=================
Outer loop
iteration 3
i= 3 j= 1
i= 3 j= 2
i= 3 j= 3
i= 3 j= 4
i= 3 j= 5
=================
Outer loop
iteration 4
i= 4 j= 1
i= 4 j= 2
i= 4 j= 3
i= 4 j= 4
i= 4 j= 5
=================
Outer loop
iteration 5
i= 5 j= 1
i= 5 j= 2
i= 5 j= 3
i= 5 j= 4
i= 5 j= 5
Explanation of the above code
§ First, the 'i' variable is initialized to 1 and
then program control passes to the i<=n.
§ The program control checks whether the condition
'i<=n' is true or not.
§ If the condition is true, then the program
control passes to the inner loop.
§ The inner loop will get executed until the
condition is true.
§ After the execution of the inner loop, the
control moves back to the update of the outer loop, i.e., i++.
§ After incrementing the value of the loop
counter, the condition is checked again, i.e., i<=n.
§ If the condition is true, then the inner loop
will be executed again.
§ This process will continue until the condition
of the outer loop is true.
Example: Write an Python Program to Print number 1 to 10, 5 times
for i in
range(1,6):
for j in
range(1,11):
print(j,end='')
# similar to new line
printing after each multiplication table
print()Output:
12345678910
12345678910
12345678910
12345678910
12345678910
Example: Write an Python Program to Print table 1 to 10,
# program to print the first ten multiplication tables
for i in
range(1, 11):
print("i
=", i, "->", end = "
")
for j in
range(1, 11):
print("{:2d}".format(i
* j), end = " ")
print() # similar to new line printing after each multiplication tableOutput:
i = 1 -> 1
2 3 4
5 6 7
8 9 10
i = 2 -> 2
4 6 8 10 12 14 16 18 20
i = 3 -> 3
6 9 12 15 18 21 24 27 30
i = 4 -> 4 8 12
16 20 24 28 32 36 40
i = 5 -> 5 10 15 20 25 30 35 40 45 50
i = 6 -> 6 12 18 24 30 36 42 48 54 60
i = 7 -> 7 14 21 28 35 42 49 56 63 70
i = 8 -> 8 16 24 32 40 48 56 64 72 80
i = 9 -> 9 18 27 36 45 54 63 72 81 90
i = 10 -> 10 20 30
40 50 60 70 80 90 100
Post a Comment