Tutorial 7/15 REPEATING ACTIONS

Python: While Loops

Master the power of repeating logic until a condition is met.

The Hook

Ever seen a Loading Spinner?
It doesn't stop until the page is ready.

Computers excel at repeating tasks. A while loop keeps going as long as a condition stays True.

Worked Example

Building a simple Countdown generator.

n = 5
# Start at 5
while n > 0:
# Keep looping passes 0
print(n)
n = n - 1
# CRITICAL: Decrease n
print("Blastoff!")
# Runs after loop ends
Active Recall

Predict Logic

We change the math. What exactly prints?

n = 1
while n < 10:
  print(n)
  n = n + 5
Level 16: Bronze

Count UP

"The code counts down. Modify it to count UP to 10. Use n = 1 and n = n + 1."

> bronze_stream_ready
Level 17: Silver

Infinite Loop Fix

"This code runs forever! Add the missing line to decrease n so the loop eventually stops."

> debugger_idle
Level 18: Gold

Guess the Number

Independent Construction Required

  • Create secret = 7 and guess = 0.
  • Loop: while guess != secret.
  • Inside: Ask for input("Guess: ") (convert to int).
  • After loop: Print "You won!".
> security_module_standby