1. While
A while loop repeats a block of code as long as a condition stays True:
condition— any expression that producesTrueorFalse; it is checked before each pass.- The block runs only while the condition is
True. When it becomesFalse, the loop stops and the program continues after it. - The block must change something the condition depends on. If nothing changes, the condition stays
Trueand the loop never ends. That is an infinite loop.
The first pass prints 3; then countdown becomes 2, the condition is checked again, and so on until countdown is 0 and 0 > 0 is False.
A variable that is initialized before the loop and updated inside it to control the condition is called a counter.
Count down with a while loop
Start n at 3. While n is greater than 0, print n and then subtract 1 from it with n -= 1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Repeat while a condition holds
Start n at 1. While n is less than 20, print n and then double it with n *= 2. The last printed value is 16, because 32 is not less than 20.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Stop when a balance reaches zero
Start balance at 150. While balance is greater than 0, print it and subtract 50 with balance -= 50.
Print exactly:
Create a free account to save your progress and unlock chapter 2.