Nested Loops: Behind the Scenes!

๐Ÿ‘‹ Welcome!

Hi! Welcome to this tutorial on Nested Loops where we will cover the basic principles with examples, let’s begin! ๐Ÿ‘

image

๐Ÿ‘€ First Example

This is the basic structure of nested for loops. We have a for loop within another for loop. Let’s see an example in action!
image

๐Ÿ“ฃ Note: Please note that you should use different variables for each loop, since you might need to use these values in your code and if you use the same variable, the value can change and result in unexpected behaviors.

image

๐Ÿ” Step by Step!

Now we have a real example of nested for loops. We have some code on the outer loop, then the inner loop and more code on the outer loop.
Let’s walk through this code step by step. You can check the code and table below for a visual reference of the process.
  • The outer loop for i in range(3) will start with an initial value of 0 for i.
  • The print statement will be executed.
  • NOW.. You will enter the inner loop! This loop will execute as usual. In the first iteration, j will have a value of 0, then on the second iteration j will have a value of 1.
  • After this inner loop has been executed, the code will return to the outer loop. In this case, the print statement on line 5 will be executed.

image
image
image

⚠️ Now...

  • ✨ This is where the magic of nested loops comes into play! The outer loop has not been executed completely.
  • ✨ We've only completed one of the three iterations required by range(3) for the outer loopTwo iterations still have to be completed. You can see below how this process is executed three times that correspond to the number of times the outer loop is executed.

image

๐Ÿ”ฎ Let's see how the values change!

You can see how the values change in this table and in the execution (above). The outer loop will be executed 3 times (because we used range(3)that goes from 0 to 2) and the inner loop will be executed completely every time the outer loop executes (each time, the inner loop will have 2 iterations because we used range(2)).

image

✅ Nested While Loops

Nested while loops work very similarly, for every iteration of the outer while loop, the inner while loop will be executed completely.
image

I hope you found this tutorial helpful ๐Ÿ˜ If you have any questions please do not hesitate to ask on the discussion forums, you classmates and Community TAs will be very glad to help you. ๐Ÿ‘
Estefania.

Comments