# Initialize Otter
import otter
grader = otter.Notebook("04_lecture_while_loops.ipynb")
While Loops in Python¶
Theme: The Parking Lot Search - Finding a spot on campus
Goal: Learn to repeat code using while loops. By the end of this notebook, you'll understand iteration, counters, running totals, sentinel values, and the break statement.
By the end of this notebook, you will be able to:
- Explain why loops are necessary (vs. repetitive manual code)
- Write condition-controlled
whileloops - Use counters to track iterations
- Accumulate running totals within loops
- Implement sentinel values for loop termination
- Use the
breakstatement to exit loops early - Recognize and prevent infinite loops
Reference: You can look back at 03_decision_structures_boolean_logic.ipynb for help with conditionals!
Important: Run cells in order from top to bottom. Later questions use variables and functions from earlier cells.
# Validation: Check Python version and file location
import os
import random
import sys
# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if current_version not in SUPPORTED_VERSIONS:
raise EnvironmentError(
f"Python version mismatch!\n"
f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
f"Found: {current_version}\n"
f"Please use Python 3.12 or 3.13 for this course."
)
print(f"Python version: {current_version}")
# Expected filename for this assignment
EXPECTED_FILE = "04_lecture_while_loops.ipynb"
# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)
if required_path_segment not in current_path and not in_allowed_env:
raise EnvironmentError(
f"File location error!\n"
f"This notebook should be in: ~/Documents/CSC115/lecture_notebooks/\n"
f"Current location: {current_path}\n"
f"Please move this file to the correct directory."
)
# Verify directory name and filename (skip in grading/development environments)
if not in_allowed_env:
if not os.path.exists(EXPECTED_FILE):
notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
raise EnvironmentError(
f"Filename mismatch!\n"
f"Expected: {EXPECTED_FILE}\n"
f"Found notebooks: {notebooks}\n"
f"Please rename your notebook to '{EXPECTED_FILE}'."
)
print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
print("Random module imported for parking simulations!")
1. The Big Picture¶
Before we dive into individual concepts, let's see what you'll be able to build by the end of this notebook. Here's a complete parking lot search simulator that uses all the concepts we'll learn:
- While loops with conditions
- Counters (tracking laps)
- Running totals (tracking time spent)
- Sentinel values ("give up" threshold)
- The
breakstatement (exit when spot found) - Random number generation
Don't worry if you don't understand it all yet! By the end of this notebook, every line will make sense.
What is random.seed()?¶
Random numbers in Python aren't truly random - they're generated by a formula that produces a sequence of numbers that appear random. The "seed" is the starting point for this sequence.
random.seed(42)- Always produces the same sequence. Great for learning because everyone gets identical results, and you can reproduce bugs!random.seed()(no argument) - Uses current time as seed, giving different results each run. More realistic but harder to debug.
For this lecture, we use a fixed seed so your output matches the examples.
# HELPER FUNCTION - Run this cell but don't modify it!
# You'll use this function in your exercises.
def check_for_spot(lot_name):
"""
Simulate checking if a parking spot is available in a campus lot.
Returns True if spot found, False otherwise.
Spot probabilities by lot:
- Purple: 10% (tiny but everyone wants it!)
- Yellow: 35%
- Red: 35%
- Teal (Mahoney-Pearson Garage): 40%
- Pink (Pavia Garage): 40%
"""
spot_chance = {
"Purple": 0.10,
"Yellow": 0.35,
"Red": 0.35,
"Teal": 0.40,
"Pink": 0.40,
}
chance = spot_chance.get(lot_name, 0.30)
return random.random() < chance
def get_lap_time():
"""
Return a random lap time between 2 and 5 minutes.
"""
return random.randint(2, 5)
print("Helper functions loaded!")
print("- check_for_spot(lot_name): Returns True if spot found")
print("- get_lap_time(): Returns random minutes (2-5) for one lap")
# THE BIG PICTURE: Complete parking search function
# By the end of this notebook, you'll understand every line!
def find_parking(lot_name, max_laps=5):
"""
Simulate searching for parking in a campus lot.
Demonstrates: while loop, counter, running total, sentinel, break
"""
# Set seed for reproducible results
random.seed(42)
# random.seed() # Uncomment for truly random behavior
laps = 0 # Counter: how many times around the lot
total_time = 0 # Running total: minutes spent searching
spot_found = False # Flag: did we find a spot?
print(f"Searching for parking in {lot_name} lot...")
# Sentinel: give up after max_laps
while laps < max_laps and not spot_found:
laps += 1 # Increment counter
lap_time = get_lap_time() # Get random lap time
total_time += lap_time # Add to running total
# Check if we found a spot
if check_for_spot(lot_name):
spot_found = True
print(f" Lap {laps}: FOUND A SPOT! ({lap_time} min)")
break # Exit immediately - no need to keep looping
print(f" Lap {laps}: No luck. ({lap_time} min)")
# Report results
print()
if spot_found:
return f"Parked in {lot_name} after {laps} lap(s). Total time: {total_time} min"
else:
return f"Gave up on {lot_name} after {max_laps} laps. Wasted {total_time} min"
# Try it out - the eternal struggle for Purple lot!
print(find_parking("Purple", max_laps=5))
print()
print("=" * 50)
print()
print(find_parking("Yellow", max_laps=5))
Now let's learn each piece!
We'll build up to this function step by step, using the universal college experience of searching for parking.
2. Why Do We Need Loops?¶
Imagine you need to check each row of a parking lot for an open spot. Without loops, you'd have to write repetitive code for each row:
# WITHOUT a loop - checking 5 rows manually
# This is tedious and error-prone!
row1_has_spot = False
row2_has_spot = False
row3_has_spot = True # Found one!
row4_has_spot = False
row5_has_spot = False
if row1_has_spot:
print("Found spot in row 1!")
if row2_has_spot:
print("Found spot in row 2!")
if row3_has_spot:
print("Found spot in row 3!")
if row4_has_spot:
print("Found spot in row 4!")
if row5_has_spot:
print("Found spot in row 5!")
# What if there are 50 rows? 100? This doesn't scale!
The problem: What if there are 50 rows? 100? Copy-pasting code is:
- Tedious and boring
- Error-prone (typos, forgetting to change numbers)
- Hard to maintain (what if the logic changes?)
The solution: Loops - code that repeats automatically!
3. The While Loop¶
A while loop repeats code as long as a condition is True.
while condition:
# This code runs repeatedly
# Something must eventually make condition False!
Key points:
- The condition is checked before each iteration ("pretest loop")
- If the condition is
Falseat the start, the loop body never runs - Something inside the loop must eventually make the condition
False, or it runs forever!
# Basic while loop: Drive through rows until we find a spot
demo_row = 1
demo_spot = False
while not demo_spot:
print(f"Checking row {demo_row}...")
# Simulate: spot found in row 3
if demo_row == 3:
demo_spot = True
print(" Found a spot!")
else:
demo_row += 1 # Move to next row
print(f"\nParked in row {demo_row}")
# Pretest behavior: if condition is False at start, loop never runs
demo_spot = True # Already found!
while not demo_spot:
print("This will never print!")
print("Loop skipped because condition was False from the start.")
Question 1: Basic While Loop (1 point)¶
Write a while loop that simulates driving through parking rows. The loop should:
- Start with
current_row = 1andspot_found = False(already provided) - Continue looping while
spot_foundisFalse - Inside the loop:
- Print which row you're checking
- If
current_rowequalstarget_row, setspot_found = True - Increment
current_rowby 1
After the loop, current_row should be one more than target_row (because we increment after finding).
# Given values (do not change)
current_row = 1
spot_found = False
target_row = 4 # The spot is in row 4
# ✏️ YOUR CODE HERE
...
...
...
spot_found = ...
...
...
print(f"\nFound spot! spot_found = {spot_found}, current_row = {current_row}")
grader.check("q1_basic_while")
4. Counters: Tracking Iterations¶
A counter is a variable that tracks how many times something has happened. Common pattern:
counter = 0 # Start at zero
while condition:
counter += 1 # Increment each iteration
# ... rest of loop
In parking terms: "How many laps around the lot have I done?"
# Count laps while searching for a spot
random.seed(2) # For reproducible results
demo_laps = 0
demo_spot = False
while not demo_spot and demo_laps < 10: # Also limit to 10 laps max
demo_laps += 1 # Increment counter
print(f"Lap {demo_laps}: Searching Yellow lot...")
if check_for_spot("Yellow"):
demo_spot = True
print("FOUND A SPOT!")
print(f"\nTotal laps: {demo_laps}")
Question 2: Using a Counter (1 point)¶
Write a while loop that counts how many rows you check before finding a spot. The loop should:
- Start with
rows_checked = 0(already provided) - Loop while
rows_checkedis less thantotal_rows - Inside the loop:
- Increment
rows_checkedby 1 - If
rows_checkedequalsspot_in_row, setfound_in_yellow = Trueand exit the loop usingbreak
- Increment
After the loop, rows_checked should equal spot_in_row.
# Given values (do not change)
rows_checked = 0
total_rows = 10
spot_in_row = 6 # The spot is in row 6
found_in_yellow = False
# ✏️ YOUR CODE HERE
...
...
...
found_in_yellow = ...
...
print(f"Checked {rows_checked} rows in Yellow lot")
print(f"Found spot: {found_in_yellow}")
grader.check("q2_counter")
5. Infinite Loops (and How to Avoid Them)¶
An infinite loop runs forever because the condition never becomes False. This is usually a bug!
Real-world parallel: Circling Purple lot forever because it's always full and you never give up.
# DANGER - This would run forever!
spot_found = False
while not spot_found:
print("Still looking...")
# Oops! We never set spot_found = True
# And we never increment anything
# This loops FOREVER
If you accidentally run an infinite loop: Click Kernel > Interrupt (or press I twice) to stop it.
# Prevention Strategy 1: Always have a way to make condition False
attempts = 0
max_attempts = 5
while attempts < max_attempts: # Will definitely become False
attempts += 1
print(f"Attempt {attempts}")
print("Loop ended safely!")
# Prevention Strategy 2: Use a maximum counter as a safety net
random.seed(999) # This seed happens to never find a spot in Purple
demo_laps = 0
demo_max_laps = 5 # Safety net!
demo_spot = False
while not demo_spot and demo_laps < demo_max_laps: # Two conditions!
demo_laps += 1
if check_for_spot("Purple"):
demo_spot = True
print(f"Lap {demo_laps}: Found spot!")
else:
print(f"Lap {demo_laps}: No spot in Purple lot")
if not demo_spot:
print(f"\nGave up after {demo_max_laps} laps. Purple lot is impossible!")
6. Running Totals: Accumulating Values¶
A running total accumulates values across iterations. Common pattern:
total = 0 # Start at zero
while condition:
total += value # Add each iteration
# ... rest of loop
In parking terms: "How much total time have I spent searching?"
# Track total time spent searching
random.seed(42)
total_time = 0 # Running total starts at 0
laps = 0
while laps < 4:
laps += 1
lap_time = get_lap_time() # Random 2-5 minutes
total_time += lap_time # Add to running total
print(f"Lap {laps}: {lap_time} min this lap, {total_time} min total")
print(f"\nSpent {total_time} minutes total searching for parking!")
Question 3: Running Total (1 point)¶
Write a while loop that calculates the total time spent searching in Red lot. The loop should:
- Start with
search_time_red = 0andlaps_in_red = 0(already provided) - Loop while
laps_in_redis less thanmax_laps_red - Inside the loop:
- Increment
laps_in_redby 1 - Add
minutes_per_laptosearch_time_red
- Increment
After the loop, search_time_red should equal max_laps_red * minutes_per_lap.
# Given values (do not change)
search_time_red = 0
laps_in_red = 0
max_laps_red = 5
minutes_per_lap = 3 # Each lap takes 3 minutes
# ✏️ YOUR CODE HERE
...
...
...
print(f"Searched Red lot for {laps_in_red} laps")
print(f"Total search time: {search_time_red} minutes")
grader.check("q3_running_total")
7. Sentinel Values: Knowing When to Quit¶
A sentinel value is a special value or condition that signals "stop looping." It's your "give up" threshold.
Examples:
- Maximum number of attempts
- Maximum time allowed
- A special input value (like "quit" or -1)
In parking terms: "Give up after 5 laps" or "Stop if I've been searching for 15 minutes."
# Sentinel value: Give up after max_laps
random.seed(999) # Value where Purple never has spots
demo_max_laps = 5 # Sentinel: our "give up" threshold
demo_laps = 0
demo_spot = False
while demo_laps < demo_max_laps and not demo_spot:
demo_laps += 1
print(f"Lap {demo_laps} of {demo_max_laps} in Purple lot...")
if check_for_spot("Purple"):
demo_spot = True
print(" Found a spot!")
if demo_spot:
print(f"\nSuccess! Parked after {demo_laps} laps.")
else:
print(f"\nGave up after {demo_max_laps} laps. Try Teal garage instead!")
# Multiple sentinels: laps AND time
random.seed(999)
demo_max_laps = 10
demo_max_time = 12 # Give up after 12 minutes
demo_laps = 0
demo_total_time = 0
demo_spot = False
while demo_laps < demo_max_laps and demo_total_time < demo_max_time and not demo_spot:
demo_laps += 1
lap_time = get_lap_time()
demo_total_time += lap_time
print(f"Lap {demo_laps}: {demo_total_time} min total")
if check_for_spot("Purple"):
demo_spot = True
# Figure out why we stopped
if demo_spot:
print("\nFound spot!")
elif demo_total_time >= demo_max_time:
print(f"\nRan out of time after {demo_total_time} minutes!")
else:
print(f"\nRan out of patience after {demo_laps} laps!")
Question 4: Sentinel Values (1 point)¶
Write a while loop that searches Teal garage (Mahoney-Pearson) with TWO stopping conditions:
- Stop if you find a spot (
teal_spot_foundbecomesTrue) - Stop if you've done
max_teal_lapslaps (sentinel value)
The loop should:
- Start with provided values
- Loop while
teal_laps < max_teal_lapsANDteal_spot_foundisFalse - Inside the loop:
- Increment
teal_laps - Use
check_for_spot("Teal")to check for a spot - If spot found, set
teal_spot_found = True
- Increment
# Given values (do not change)
random.seed(50) # For reproducible results
teal_laps = 0
max_teal_laps = 6
teal_spot_found = False
# ✏️ YOUR CODE HERE
...
...
...
teal_spot_found = ...
...
...
...
print(f"\nResult: spot_found={teal_spot_found}, laps={teal_laps}")
grader.check("q4_sentinel")
8. The break Statement: Exit Immediately¶
The break statement exits the loop immediately, even if the condition is still True.
When to use break: When you find what you're looking for and continuing would waste time.
In parking terms: "I found a spot! Stop driving around!"
# Without break: we'd always do all 10 laps
# With break: we stop as soon as we find a spot
random.seed(42)
laps = 0
max_laps = 10
while laps < max_laps:
laps += 1
print(f"Lap {laps}: Searching Pink garage (Pavia)...")
if check_for_spot("Pink"):
print(f" FOUND A SPOT on lap {laps}!")
break # Exit immediately!
print(f"\nLoop ended after {laps} laps")
print(f"Without break, we would have done all {max_laps} laps.")
# Compare: with vs without break
random.seed(42)
# WITH break
laps_with_break = 0
while laps_with_break < 10:
laps_with_break += 1
if check_for_spot("Pink"):
break
# WITHOUT break (using flag instead)
random.seed(42) # Reset seed for fair comparison
laps_without_break = 0
demo_found = False
while laps_without_break < 10 and not demo_found:
laps_without_break += 1
if check_for_spot("Pink"):
demo_found = True
print(f"With break: stopped at lap {laps_with_break}")
print(f"With flag: stopped at lap {laps_without_break}")
print("Both work! Break is often cleaner when you just want to exit.")
Question 5: Using Break (1 point)¶
Write a while loop that searches Yellow lot and uses break to exit when a spot is found. The loop should:
- Loop while
yellow_laps < max_yellow_laps - Inside the loop:
- Increment
yellow_laps - Add
lap_durationtoyellow_search_time - Use
check_for_spot("Yellow")to check for a spot - If spot found, set
parked_in_yellow = Trueand usebreakto exit
- Increment
With the given seed, you should find a spot before reaching max_yellow_laps.
# Given values (do not change)
random.seed(88)
yellow_laps = 0
max_yellow_laps = 8
yellow_search_time = 0
lap_duration = 4 # 4 minutes per lap
parked_in_yellow = False
# ✏️ YOUR CODE HERE
...
...
...
...
parked_in_yellow = ...
...
print(f"Laps: {yellow_laps}, Time: {yellow_search_time} min, Parked: {parked_in_yellow}")
grader.check("q5_break")
9. Brief Note: The continue Statement¶
The continue statement skips the rest of the current iteration and jumps to the next one.
Example use case: Skip reserved rows (faculty parking) without exiting the entire loop.
# Skip reserved rows using continue
reserved_rows = [2, 5] # Faculty only!
demo_row = 0
while demo_row < 7:
demo_row += 1
if demo_row in reserved_rows:
print(f"Row {demo_row}: RESERVED - skipping")
continue # Skip to next iteration
print(f"Row {demo_row}: Checking for spots...")
Note: We'll practice continue more in the lab. For now, just know it exists and skips to the next iteration.
10. Putting It All Together¶
Now you understand all the pieces! Look back at the find_parking() function at the top - every line should make sense now:
laps = 0- Counter initializationtotal_time = 0- Running total initializationwhile laps < max_laps and not spot_found:- Sentinel + conditionlaps += 1- Increment countertotal_time += lap_time- Accumulate running totalbreak- Exit immediately when spot found
Stretch Goal: Campus Shuttle Wait Time (1 bonus point)¶
Let's apply what you've learned to a different scenario: waiting for the campus shuttle!
You're waiting for the Stanford Route shuttle. Each shuttle arrives every 6 minutes, but sometimes it's full and you can't board.
Write a while loop that simulates waiting for the shuttle:
- Start with provided values
- Loop while
shuttle_wait_time < max_shuttle_waitANDfull_shuttles < max_full_shuttlesANDboarded_shuttleisFalse - Inside the loop:
- Add
shuttle_intervaltoshuttle_wait_time(running total) - Use the provided
random.random() < 0.70check (70% chance shuttle has space) - If shuttle has space: set
boarded_shuttle = Trueandbreak - If shuttle is full: increment
full_shuttles(counter)
- Add
Concepts used: While loop, counter, running total, sentinel values, break
# Given values (do not change)
random.seed(77)
shuttle_wait_time = 0 # Running total: minutes waited
full_shuttles = 0 # Counter: how many full shuttles passed
max_shuttle_wait = 25 # Sentinel: give up after 25 minutes
max_full_shuttles = 3 # Sentinel: give up after 3 full shuttles
shuttle_interval = 6 # Minutes between shuttles
boarded_shuttle = False
print("Waiting for Stanford Route shuttle...")
# ✏️ YOUR CODE HERE
...
...
...
boarded_shuttle = ...
...
...
...
...
...
# Report what happened
print()
if boarded_shuttle:
print(f"Boarded Stanford Route after {shuttle_wait_time} min!")
elif full_shuttles >= max_full_shuttles:
print(f"Gave up after {full_shuttles} full shuttles. Walking instead!")
else:
print(f"Waited {shuttle_wait_time} min - too long! Taking the RSMAS shuttle instead.")
grader.check("q6_stretch_shuttle")
Summary¶
Congratulations! You've learned how to repeat code using while loops!
| Concept | Syntax | Example |
|---|---|---|
| Basic while | while condition: |
while not found: |
| Counter | count += 1 |
laps += 1 |
| Running total | total += value |
total_time += lap_time |
| Sentinel | threshold in condition | while laps < max_laps: |
| Compound condition | and, or |
while laps < 5 and not found: |
| Break | break |
Exit loop immediately |
| Continue | continue |
Skip to next iteration |
| Random seed | random.seed(n) |
Reproducible randomness |
Key Takeaways¶
- While loops repeat code until a condition becomes
False - Counters track iterations - don't forget to increment!
- Running totals accumulate - start at 0, add each iteration
- Sentinels prevent infinite loops - always have an exit strategy
- Break exits immediately - use when you find what you need
- Test your loops - make sure they actually terminate!
What's Next?¶
- Lab: Practice these patterns with a Wordle solver
- Next Week:
forloops - when you know exactly how many iterations you need- Teaser: Remember how we searched one lot at a time? Next week you'll learn how to loop through a list of lots automatically!
You have completed the While Loops notebook!
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()