DEV Community 👩‍💻👨‍💻

Cover image for Shortcut to solve Questions related to for loop.
Keshav Jindal
Keshav Jindal

Posted on

Shortcut to solve Questions related to for loop.

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 in a easy way
Let first for loop condition to be Days & other loop conditions to be sessions. That basically means that a student has to sit in all sessions everyday.

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)
Iteration1:
i=0, condition become True and loop will be connected
Day will be Monday. There are 6 sessions in j and a student has to sit in all sessions every day.
So, result will come to be 0 1 2 3 4 5
Iterations3:
i = 2, condition become True and 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:
Iteration1:
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, output become 0 1 2 3
Iteration3:
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)

DEV has this feature:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠