Loop Control Slides
Technical Share-Out Series Slide 1 of 17
Control Flow & Iteration
Loop Control Mastery
An interactive walkthrough of while, for, range(), nested loops, and recursion.
Ready to Trace
AP CS A / CS1 Aligned
Introduction Slide 2 of 17
Why Do We Loop?
Writing repetitive code violates the core software engineering principle: DRY (Don't Repeat Yourself).
Avoid Redundancy Repeated lines make programs bloated and incredibly difficult to maintain.
IT Systems Application Automating live tasks like processing system log streams, pagination API queries, or retrying broken server connections.
Inefficient
# Sending 5 emails manually
send_email("user1@test.com")
send_email("user2@test.com")
send_email("user3@test.com")
send_email("user4@test.com")
send_email("user5@test.com")
Dynamic & Dry
# Dynamic mailing via loop
for email in email_list:
send_email(email)
Unit 3: Iteration Lenny Computer Science
While Loops Slide 3 of 16
The while Loop
A while loop continues to execute its block of code as long as its boolean condition remains True.
The Infinite Loop Trap
If the loop condition never becomes False, your program gets stuck forever! You must update loop control variables.
Syntax & Mechanics
# 1. Initialize control variable
count = 1
# 2. Test boolean condition
while count <= 3:
print(count)
# 3. Modify variable (prevent infinite loop)
count += 1
Infinite Loop Avoidance Keep Conditions Dynamic
Interactive Check Slide 4 of 16
Topic 1 Quiz: while & continue
What is the final result of val?
Trace how the continue control statement affects variable updates. When k == 4 is met, what segment of code is bypassed?
Interactive Audience Poll
Shout out or write in chat: is the final output (A) 25, (B) 9, (C) 13, or (D) 21? Trace each transition carefully.
val = 1
k = 12
while k > 2:
k -= 4
if k == 4:
continue
val += k
print(val)
Answer Revealed: k=8 (adds 8 -> val=9). k=4 (hits continue, skips val update). k=0 (adds 0 -> val=9). val = 9.
Topic 1 Active Quiz State Accumulation with Continue
Code Tracing Slide 5 of 16
Trace This Code
Follow the variable updates step-by-step through each iteration of the loop.
x = 10
y = 0
while x > y:
x -= 2
y += 3
Dry-Run Tracing Table
| Iteration | x | y | x > y ? |
|---|
| Pre-loop | 10 | 0 | 10 > 0 (True) |
| 1 | 8 | 3 | 8 > 3 (True) |
| 2 | 6 | 6 | 6 > 6 (False) |
The loop exits after 2 iterations because 6 > 6 evaluates to False. Final values: x = 6, y = 6.
Visual Variable Tracing State Tracking
For Loops & Ranges Slide 6 of 16
The for Loop & range()
A for loop iterates over a defined sequence. The built-in range() function generates an immutable sequence of arithmetic progressions.
Key rule: The stop index is exclusive—the loop stops before it hits that value!
The Three range() Forms
range(stop) Starts at 0, counts up to stop-1
range(start, stop) Starts at start, counts up to stop-1
range(start, stop, step) Increments or decrements by step value
Exclusive Boundary Rules Sequence Generation
Range Examples Slide 7 of 16
Execution Output Tracing
# Example A: One argument
for i in range(4):
print(i)
# Example B: Two arguments
for j in range(5, 8):
print(j)
# Example C: Negative step (decrement)
for k in range(10, 4, -2):
print(k)
Sequence Generated
Ex A:
0 1 2 3 4
Ex B:
5 6 7 8
Ex C:
10 8 6 4
Notice: For decrements (negative steps), start must be larger than stop, and stop remains strictly non-inclusive!
Step Increments / Decrements Inclusive vs Exclusive Boundaries
Iterating Collections Slide 8 of 16
Looping Lists & Strings
Unlike other languages, Python's for loops iterate directly over the elements of any iterable, rather than relying on index variables.
Lists are collections of items processed in order. Strings are treated as sequences of characters, stepping through each index automatically!
List Iteration
for task in ["Auth", "Audit"]:
print(task)
Output: "Auth" "Audit"
String Iteration
for char in "IT":
print(char)
Output: 'I' 'T'
Direct Sequence Traversal Lists and Strings Iterators
Interactive Check Slide 9 of 16
Topic 2 Quiz: range & break
What is the final result of total?
Look closely at the decrement step size and boundaries. When the loop hits i == 7, the break triggers. How does this alter the output?
Peer share-out challenge
Turn to your peer. Explain: what value of total would result if the break statement were bypassed entirely?
total = 100
for i in range(15, 3, -4):
if i == 7:
break
total -= i
print(total)
Answer Revealed: i takes: 15 (total=85), 11 (total=74). When i=7, break exits the loop. total = 74.
Topic 2 Active Quiz Exclusive Negative Steps with Break
Nested Loops Slide 10 of 16
Nested Loops
A nested loop is a loop inside another loop.
For each single iteration of the outer loop, the inner loop runs completely from start to finish!
Perfect for multi-dimensional data structures, grids, spreadsheets, or coordinated coordinate mapping (row and col).
Tracing Row & Col
for row in range(1, 3):
for col in range(1, 4):
print(f"({row},{col})", end=" ")
print()
Output Screen:
Row 1: (1,1) (1,2) (1,3)
Row 2: (2,1) (2,2) (2,3)
Loops inside Loops Multi-Dimensional Control Flow
Interactive Check Slide 11 of 16
Topic 3 Quiz: Nested & continue
What is the final result of sum_vals?
Trace the multi-dimensional coordinate loops. When x == 5 and y == 1, the inner loop continue activates. How many values are skipped?
Computer Science Bonus Check
What is the Big-O Time Complexity of nested loop traversals like this over collections of size N and M? Answer: \(O(N \times M)\)—quadratic execution time!
sum_vals = 0
for x in [2, 5]:
for y in [1, 3]:
if x == 5 and y == 1:
continue
sum_vals += (x * y)
print(sum_vals)
Answer Revealed: x=2: (2*1) + (2*3) = 8. x=5: skips y=1. Adds (5*3) = 15. sum_vals = 8 + 15 = 23.
Topic 3 Active Quiz Multi-Loop Traversal with Continue
Loop Alterations Slide 12 of 16
Loop Control Statements
break statement
Terminates the loop structure immediately and forces program execution to skip to the next code block after the loop.
continue statement
Skips the remaining statements in the current iteration and forces the loop to begin the next iteration immediately.
# Control Execution Tracing
for num in range(1, 6):
if num == 3:
continue # Skip 3
if num == 5:
break # Terminate loop at 5
print(num)
CONSOLE OUTPUT:
1 2 3 4 5
Break vs Continue Execution Flow Disruption
Design Decision Slide 13 of 16
When to Use for vs while?
Definite Iteration (for)
Use when the number of iterations is known or fixed beforehand (e.g. iterating over lists, files, ranges).
- Looping over an array of 50 states
- Summing odd numbers from 1 to 99
- Iterating over the characters of a word
Indefinite Iteration (while)
Use when the number of iterations depends on an event or dynamic condition during execution.
- Asking a user to type input until valid
- Waiting for a web request to complete
- A game loop running until "game over" is True
Architectural Best Practices Definite vs Indefinite Iteration
Recursion Slide 14 of 16
Recursion: Self-Reference
Recursion is a technique where a function calls itself to solve a smaller subproblem of the original problem.
1
Base Case
The condition under which the function stops calling itself (avoids infinite stack overflow).
2
Recursive Case
The part of the function where it calls itself with a modified, smaller argument.
Recursive Factorial Structure
def factorial(n):
# 1. Base Case
if n == 1:
return 1
# 2. Recursive Case
else:
return n * factorial(n - 1)
Alternative to Traditional Loops The Call Stack Mechanics
Recursion Tracing Slide 15 of 16
Tracing factorial(4)
Call #1
factorial(4)
n is 4 (Recurse)
4 * 6 = 24
Call #2
factorial(3)
n is 3 (Recurse)
3 * 2 = 6
Call #3
factorial(2)
n is 2 (Recurse)
2 * 1 = 2
Call #4 (Base)
factorial(1)
Base Case Reached!
Returns 1
Calls unwind from right to left! The base case resolves first, sending values back up the stack to solve the original computation.
Call Stack Wind and Unwind Base Case Resolution
Branching Recursion Slide 16 of 17
The Fibonacci Sequence
Unlike Factorial's linear path, recursive fib(n) makes two calls per step, drawing a branching execution tree!
Redundant Calculations Notice how fib(2) is computed multiple times in this tree! In larger values, this creates exponential \(O(2^N)\) time complexity.
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
Execution Call Tree for fib(4)
fib(4)
/
fib(3)
/
fib(2)
\
fib(1)
\
fib(2)
/
fib(1)
\
fib(0)
Branching Recursion Trees Exponential Time Complexity Checks
Quick Quiz Slide 17 of 17
What Have We Mastered?
Question 1
What values are generated by the sequence function range(2, 10, 3)?
Values: 2, 5, 8
Question 2
In a nested loop structure, which loop completes all iterations first?
The inner loop
Question 3
What happens if a recursive call stack is missing a base case?
RecursionError (Stack Overflow)
Ready for hands-on practice? Grab the Loop Control Tracing Worksheet to try it yourself!
Classroom Discussion Mastery Achieved!