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! ๐
๐ 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!
๐ฃ 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.
๐ 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 of0
fori
. - 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 of0
, then on the second iterationj
will have a value of1
. - After this inner loop has been executed, the code will return to the outer loop. In this case, the
print
statement online 5
will be executed.
⚠️ 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 loop. Two 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.
๐ฎ 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)
).✅ 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.
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
Post a Comment