while, break and the Loop That Never Ends
Sometimes you cannot know in advance how many times to repeat. Keep asking until the answer is a number. Keep adding until the savings reach the target. A while loop repeats its block as long as a condition stays True, which also means that, if the condition never changes, it repeats forever.
Think of stirring a sauce until it thickens. You do not count the stirs; you check after each one. Forget to check, and you would stir all night. A while loop is that instruction, with the checking built in.
while condition
A while line has a condition and a colon, like an if. Before each round, Python checks the condition. If it is True, the block runs, and then Python checks again. The first time it is False, the loop ends and the program carries on. In the program below, the savings grow by 150 a month until they reach 1000.
savings = 0 months = 0 while savings < 1000: savings = savings + 150 months = months + 1 print(f"{months} months to save {savings}")
7 months to save 1050
The Loop That Never Ends
The condition must depend on something that changes inside the loop. Leave out the line that changes it and the condition stays True forever: the program keeps going and never finishes. Nothing is damaged; your program is just busy. Press Control and C in the terminal to stop it. Python stops at once and reports a KeyboardInterrupt, which only means "stopped by the keyboard". Exactly where the two characters ^C appear, and which line the report names, depends on the moment you pressed the keys.
savings = 0 while savings < 1000: print("Saving...")
Saving...
Saving...
Saving...
^CTraceback (most recent call last):
File "/Users/you/python-course/forever.py", line 3, in <module>
print("Saving...")
~~~~~^^^^^^^^^^^^^
KeyboardInterrupt
break and continue
Two words change a loop's flow from inside. break leaves the loop immediately, whatever the condition says. continue skips the rest of this round and goes straight to the next check. A common shape is while True with a break: loop forever, and leave the moment the job is done.
Ask Until the Answer Is Valid
Chapter 2's tip calculator crashed when someone typed a word. With a loop it can ask again. The isdigit method answers True when a string is made only of digits. The loop below keeps asking until it is, then breaks out and converts the answer safely. Chapter 8 shows a more complete way to handle bad input; this is the first step.
while True: answer = input("Tip percent: ") if answer.isdigit(): break print("Please type a whole number, like 15.") percent = int(answer) print(f"Tip set to {percent} percent")
Tip percent: forty Please type a whole number, like 15. Tip percent: 15 Tip set to 15 percent
- "while and for are interchangeable."
forwalks through a collection you already have.whilerepeats until a condition changes, when you cannot know the number of rounds in advance. - "An endless loop can damage the computer." It only keeps your program busy. Control and C stops it.
- "break ends the whole program." It ends the loop it is in. The program carries on with the first line after that loop.
- "
isdigitaccepts any number." It accepts only digits, so a minus sign or a decimal point makes it answer False. Chapter 8 handles those cases properly.
- Asking again after bad input is the first step to a program other people can actually use.
- Knowing that Control and C stops anything removes the fear of running a program that might not finish.
Knowledge Check
When does a while loop stop?
- After it has run exactly ten rounds
- When its condition is False, or at a break
- When the block has run once for every item
- When the program reaches the end of the file
What does break do inside a loop?
- Stops the program and prints an error message
- Skips to the next round of the same loop
- Leaves the loop at once and carries on after it
- Pauses the loop until the person presses a key
A program runs forever and never finishes. How do you stop it?
- Type exit() and press Enter in the terminal
- Press Control and C in the terminal
- Wait, because Python stops long loops after a minute
- Delete the file, and the program will stop
Why does while savings < 1000: need a line that changes savings?
- Python refuses a while loop that has no assignment
- The change makes the loop run faster each round
- Otherwise savings would be reset to zero each round
- Without it the condition never turns False
You got correct