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 a break to stop.
  • The condition after if decides when to leave.
  • break is useful when the exit condition is easier to check in the middle of the block than at the top.
#01

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.

#02

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.

#03

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.