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.
Predict Logic
We change the math. What exactly prints?
while n < 10:
print(n)
n = n + 5
Count UP
"The code counts down. Modify it to count UP to 10. Use n = 1 and n = n + 1."
Infinite Loop Fix
"This code runs forever! Add the missing line to decrease n so the loop eventually stops."
Guess the Number
Independent Construction Required
- Create
secret = 7andguess = 0. - Loop:
while guess != secret. - Inside: Ask for
input("Guess: ")(convert toint). - After loop: Print "You won!".