1.Introduction to For loop
For loop is used to iterate over a sequence. With the help of for loop
all the items present in the sequence are accessed one by one.
2.Trick to solve nested loop
questions easily
Let the first loop
condition be Days and the other loop
conditions be sessions. Linking this analogy to the daily life of a student- a student has to sit in all sessions every day.
For example-
for i in range(3):
for j in range(6):
print(j, end=' ')
TRICK TO SOLVE ABOVE QUESTION:
Let i = Days(Monday, Tuesday, etc..) &
j = Sessions(Mathematics, Science, etc..)
range for i = (0,1,2)
range for j = (0,1,2,3,4,5)
Iteration 1:
i=0, the condition becomes True and the loop
will be connected and the day will be Monday. There are 6 sessions in j, and a student must sit in all sessions daily.
So, the result will be: 0 1 2 3 4 5
Iterations 2:
i = 2, the condition becomes True and the day will be Wednesday. Result: 0 1 2 3 4 5
Final Output:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
Example 2:
my_string =['Mathematics','Science','History']
for i in range(len(my_string)):
for x in range(4):
print(x, end=(' '))
Explanation:
Iteration 1:
Range for i = (0,1,2)
Range for x = (0,1,2,3)
i = 0, Day 1 i.e Monday, we have to sit in all sessions So, the output becomes: 0 1 2 3
Iteration 3:
i = 2, Day 3 is Wednesday and after sitting in all sessions, output comes out to be: 0 1 2 3.
Final output
0 1 2 3 0 1 2 3 0 1 2 3
Top comments (0)