While Loops
A while loop repeats its body while a condition is true. Python checks the condition before each repetition and stops when it is false.
The shape of a while loop
counter = 1while counter <= 3: print(counter) counter = counter + 1print("finished")This prints 1, 2 and 3 on separate lines, then finished.
When the condition is true, Python runs the indented body, then checks again. After the third repetition, counter is 4. The check is false, so Python moves on to the line after the loop.
The line counter = counter + 1 moves the loop toward its stop. Without it, counter stays 1 and the loop never ends. If the condition is false at the first check, the body runs zero times.
Stop with a flag
A flag is a True/False variable that records whether something has happened. Start it as False, set it to True inside the loop, and let the condition check it.
number = 1found = Falsewhile not found and number <= 10: if number * 7 > 30: found = True else: number = number + 1if found: print(number)else: print("None found")This prints 5, because 5 * 7 is 35, the first one over 30. The loop stops when found becomes True, or when number passes 10. After the loop, if found: tells you which one happened.
while or for?
Use for to visit each item in a list or range(). Use while when a condition decides how long to repeat, such as "until the guess is right".
See also: For loops, break and continue, Comparisons and Logical Operators.
Your turn
Use a while loop to print the multiples of 3 that are less than 10. Print number, then add 3 to it.
3 6 9
number = 3# Add the loop here.Advanced reading
- Processing a work list — loop until a list is empty, adding and removing items as you go.
- The walrus operator in while loops — read and test a value in one condition with
:=.