Python - 12
Python - 12: While Loops
while loops repeat code as long as a condition remains true.
Your challenge: Count from 1 to 5 with a while loop, then create another loop that counts down.
Check the condition
This loop keeps running while count <= 5 is true.
Once count becomes 6, the condition is false and the loop stops.
Update the variable
Inside the loop, count = count + 1 increases the value each time.
Without that update, the condition could stay true forever.
Count down
You can also decrease a value: lives = lives - 1
Try it: Change the first loop so it counts from 1 to 10.
Good Python habit: Before running a while loop, make sure something inside the loop will eventually make its condition false.
👀 Show Example Solution
count = 1
while count <= 5:
print(count)
count = count + 1
print("Loop finished!")
lives = 3
while lives > 0:
print("Lives left:")
print(lives)
lives = lives - 1
print("Game Over!")A while loop keeps checking its condition after every repetition and stops when that condition becomes false.
