DEV Community

Cover image for Nested loop practice.
Keshav Jindal
Keshav Jindal

Posted on • Edited on

3 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay