Concept
As per this lesson, you may find yourself wanting to combine loops like for
and while
. However in doing so, it is important to understand how they will interact when nested.
Mechanics
There are a few key issues that I have seen pop up regularly in questions:
The first if you have two for
loops, the inner for
loop will run completely for each step in the outer for
loop. Example:
list1 = [1,2,3]
list2 = ['a', 'b', 'c']
for n in list1:
for L in list2:
print(str(n) + L)
#output: 1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c
As you can see, it cycles through all of the second loop before moving on to #2 in the first loop. This also demonstrates that a variable used in the outer loop can be used in the inner loop. Variables from the inner loop can be used in the outer loop but only after being defined (this could be useful if you were creating a list for example).
On the other hand, an outer while
will not be checked during the running of an inner loop.
i = 0
while i < 2:
for n in range(0,6):
i = n
print(i)
#output: 0, 1, 2, 3, 4, 5
As you can see, the inner for
loop will run to completion ignoring the while
loop even though you may have expected it to stop once i
was 2.
These are just a couple examples that will hopefully help solve issues with your own code. Please discuss below and help each other to further solve challenges that arise.