Flow control

Break and continue

In a while loop (or any loop like for), break and continue are control flow statements that affect how the loop operates, but they work in different ways:

1. break:

It immediately terminates the loop. When break is encountered, the program exits the loop entirely and continues executing the code that follows the loop.
  
Example:

  i = 1
  while i <= 5:
      if i == 3:
          break  # Loop will exit when i is 3
      print(i)
      i += 1

Output:

  1
  2

Here, when i becomes 3, the break statement is executed, causing the loop to end.


2. continue:

It skips the current iteration of the loop and moves on to the next iteration.
When continue is encountered, the rest of the code inside the loop for the current iteration is skipped, but the loop continues from the next iteration.

Example:

  i = 1
  while i <= 5:
      i += 1
      if i == 3:
          continue  # Loop will skip printing when i is 3
      print(i)
  
 Output:

  2
  4
  5
  6

Here, when i is 3, the continue statement is executed, so the print(i) statement is skipped for that iteration, but the loop continues for the next iterations.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What does the break statement do in a loop?

It causes an error
It skips the current iteration of the loop
It immediately terminates the loop
It restarts the loop from the beginning
Check Answer

What does the continue statement do in a loop?

It skips the current iteration and moves to the next one
It exits the loop completely
It restarts the loop from the beginning
It causes an error
Check Answer

What will be the output of the following code? i = 1 while i <= 5: i += 1 if i == 3: continue print(i)

2 3 4 5
1 2 3 4 5
1 2 4 5
2 4 5
Check Answer