2. Break
break is a statement that ends the loop that contains it immediately. The program continues with the first line after the loop; it does not stop the whole program.
while True:means "loop forever", so the loop needs abreakto stop.- The condition after
ifdecides when to leave. breakis useful when the exit condition is easier to check in the middle of the block than at the top.
Break out of a while True loop
Use while True. Start n at 1, print n, and break when n is 3. Add 1 to n after the check.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Break before printing
Start n at 1. While n is less than or equal to 10, break when n is 4; otherwise print n. Add 1 to n after printing.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Stop searching a list
Use words = ["apple", "banana", "stop", "cherry"] and a counter i starting at 0. While i is less than len(words), break when words[i] is "stop"; otherwise print the word. Add 1 to i after printing.
Print exactly:
Create a free account to save your progress and unlock chapter 2.