Presentation is loading. Please wait.

Presentation is loading. Please wait.

Nested Loops. Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures.

Similar presentations


Presentation on theme: "Nested Loops. Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures."— Presentation transcript:

1 Nested Loops

2 Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures can be nested inside each other to any degree you need

3 Nested loops The general principle of nesting loops is that the inner loop must completely finish its execution before the next iteration of the outer loop starts Every time the outer loop iterates, the inner loop needs to start the control variable back at the beginning again

4 Nested for loops for i in range(10): for j in range(5): print(i, j) The nesting is shown by the indentation Different variables are used for the two loops, i and j, for clarity Other statements can be inside the outer loop, not just the inner loop

5 Nested while loops These work on the same principles as the for loops If they are controlled by counters, make sure the initializations of the counters are where they need to be. That is, if the inner loop needs to have its counter set to zero before the loop, you must decide whether the initialization needs to be inside the outer loop or outside the outer loop ct1 = 0 while ct1 < 5: ct2 = 0 while ct2 < 10: print(ct1, ct2) ct2 += 1 ct1 += 1


Download ppt "Nested Loops. Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures."

Similar presentations


Ads by Google