DEV Community

Cover image for Nested loop practice.
Keshav Jindal
Keshav Jindal

Posted on • Updated on

Nested loop practice.

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 loopquestions easily
Let the first loopcondition be Days and the other loopconditions 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=' ')
Enter fullscreen mode Exit fullscreen mode

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 loopwill 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=(' '))
Enter fullscreen mode Exit fullscreen mode

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)