2. Nested Loops
A nested loop is a loop inside the body of another loop
Inner (inside), outer (outside) loops:
for row in range(1, 3, 1): //outer
for col in range(1, 3, 1)://inner
print(row * col)
Inner loop goes through all repetitions for each repetition of
outer loop
Inner loop repetitions complete sooner than outer loop
Total number of repetitions for inner loop is product of number
of repetitions of the two loops.
Can nest different styles of loops together
3. Nesting Loops
Nested loops are necessary when a task is performs a repetitive
operation and that task itself must be repeated.
for initialize in range(start, stop, update): while(condition):
for initialize in range(start, stop, update):
while(condition):
Just like when we worked with nested conditionals
if (condition):
if (condition):
For example, a digital clock is a good example of needing to nest
for loops.
4. Digital Clock
How can we use loops to simulate a digital clock?
What would each loop be responsible for keeping track of?
There would be 3 loops:
One would track the hour
One would track the minutes
One would track the seconds
NOT AN ANALOG CLOCK, why??????
What would it look like?
5. Digital Clock
First let’s begin by creating a loop to display the seconds up to
a minute.
Can anyone describe that loop???
for sec in range(0, 60, 1):
print(format(sec, ‘>2’)
Question: What is the initialization, test and update for the
previous for loop?
Question: What would it look like if we printed to the left with
setw(2)?
6. Digital Clock
Now let’s add minutes by nesting our previous loop:
for min in range(0, 60, 1):
for sec in range(0, 60, 1):
print(format(min, ‘>2’), ”:”, format(sec, ‘>2’)
7. Digital Clock
for hour in range(0, 12, 1):
for min in range(0, 60, 1):
for sec in range(0, 60, 1):
print(format(hour, ‘>2’), ”:”, format(min, ‘>2’), ”:”, format(sec, ‘>2’)
Question: What if we wanted to add AM/PM
8. Digital Clock
Assign 0 to
hour
hour <
12
Assign 0 to
sec
Assign 0 to
min
True
False
min <
60
False
True
sec <
60
Fals
True Print clock
9. Infinite Loops
Loops must contain a way to terminate otherwise the loop will
continue to repeat until the program is interrupted.
Infinite loops usually occur when the programmer forgets to write
code inside the loop making the Boolean expression false.