Concepts / Loop Control with break and continue

Loop Control with break and continue

We move the raw_input and if statements to inside the while loop and set the variable running to True before the while loop. First, we check if the variable running is True and then proceed to execute the corresponding while-block . After this block is executed, the condition is again checked which in this case is the running variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.

  • Programming

Why Loop Control Matters

When you write a loop, you often need to respond to events that happen inside the loop. Sometimes you want to stop the loop entirely when a certain condition is met. Other times, you want to skip the rest of the current iteration and jump straight to checking the loop condition again. These two needs are so common that every programming language provides two statements to handle them: break and continue. Understanding exactly what each one does—and when execution goes after they run—is essential to writing loops that behave the way you intend.

How a While Loop Normally Executes

Before we introduce break and continue, let's trace through the normal execution of a while loop. You set a variable (often called running) to True before the loop starts. Then the loop checks the condition: if running is True, the while-block executes. After the block finishes, the condition is checked again. If it is still True, the block runs again. This repeats until the condition becomes False. At that point, the loop exits and the optional else-block executes (if one exists). Then the program continues to the next statement after the loop.

TrueTrueFalseFalseCheck conditionExecute while-blockCheck condition againExecute else-block(if present)Continue to nextstatement
What is the sequence of steps in a normal while loop, from the condition check through block execution to the next iteration or else block?

The break Statement: Exit Immediately

The break statement is used to break out of a loop statement—that is, to stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has not been completely iterated over. When break executes, the loop terminates at that instant. Execution jumps directly to the first statement after the loop, completely skipping the else-block (if one exists) and any remaining iterations.

break does two things: it stops the loop immediately, and it prevents the else-block from running. If you want the else-block to run only when the loop completes normally (not via break), this is the behavior you want.

The continue Statement: Skip to Next Iteration

The continue statement is used to skip the rest of the current iteration and jump directly to the next condition check. When continue executes, any code that comes after it in the while-block is skipped. The loop condition is checked again immediately. If the condition is still True, the while-block runs again from the beginning. If the condition is False, the loop exits normally and the else-block runs (if one exists).

continue does not exit the loop—it only skips the rest of the current iteration. The loop continues to run, and the else-block will still execute when the loop condition finally becomes False.

Execution Flow: break vs. continue

TrueYesNoYesNoFalseCheck conditionExecute while-blockbreak encountered?continue encountered?Exit loop (skip else)Jump to conditioncheckExecute else-block(if present)Continue to nextstatement
When break or continue executes inside a loop, where does execution go next—does the loop restart, exit completely, or skip to the next iteration?

Worked Example: Using break to Exit Early

Searching for a Target Value

Write a loop that reads numbers from the user and stops as soon as the user enters the number 0. After the loop exits, print a message saying the loop has ended.

Set up the loop control variable: Before the loop, set running = True. This ensures the while condition is True the first time it is checked.

Check the condition and read input: Inside the while-block, use raw_input to get a number from the user. Convert it to an integer.

Decide whether to break: Use an if statement to check if the number equals 0. If it does, execute break. This exits the loop immediately without running the else-block.

Process normal input: If the number is not 0, print it or process it. Then the loop goes back to check the condition.

After the loop: Because we used break, the else-block (if present) is skipped. The program continues to the next statement after the loop.

The loop reads numbers until the user enters 0, then exits immediately. The else-block does not run because break was used.

Worked Example: Using continue to Skip Iterations

Processing Valid Input Only

Write a loop that reads numbers from the user. Skip any negative numbers (do not process them). When the user enters 0, stop the loop and print a summary message.

Set up the loop control variable: Set running = True before the loop so the while condition is True initially.

Read input inside the loop: Use raw_input to get a number from the user and convert it to an integer.

Check for the exit condition: If the number is 0, set running = False. This causes the loop condition to become False on the next check, and the loop exits normally (the else-block runs).

Skip negative numbers with continue: If the number is negative, execute continue. This skips the rest of the while-block and jumps back to check the condition. Negative numbers are not processed.

Process positive numbers: If the number is positive and not 0, process it (print it, add it to a sum, etc.). Then the loop checks the condition again.

Execute the else-block: Because we used running = False instead of break, the loop exits normally and the else-block runs, printing the summary message.

The loop processes only positive numbers, skips negative ones, and exits cleanly when 0 is entered. The else-block runs because break was not used.

The else Block and Loop Control

The else block is executed when the while loop condition becomes False. This may even be the first time that the condition is checked. If there is an else clause for a while loop, it is always executed unless you break out of the loop with a break statement. Remember that the else part is optional. When included, it is always executed once after the while loop is over unless a break statement is encountered.

The else-block is a signal that the loop completed normally. If you use break to exit early, the else-block is skipped. If you use continue or let the condition become False naturally, the else-block runs.

Common Mistakes with break and continue

  • Forgetting that break skips the else-block

    break exits the loop immediately and skips the else-block entirely. The else-block only runs if the loop condition becomes False naturally or if you use continue and eventually the condition becomes False.

    Fix: If you need a summary to print regardless of how the loop exits, put that code after the loop (outside the else-block), or use a different control flow strategy that does not rely on break.

  • Using continue when you meant to use break

    continue only skips the rest of the current iteration and jumps back to the condition check. It does not stop the loop. The condition is still True, so the loop runs again.

    Fix: Use break to exit immediately, or set the loop control variable to False (e.g., running = False) so the condition becomes False on the next check.

  • Placing break or continue outside the loop

    break and continue only work inside a loop. If they are not indented inside the loop body, Python will raise a SyntaxError because these statements have no loop to control.

    Fix: Ensure break and continue are indented inside the while-block (or for-block) that you want to control.

  • Confusing the loop control variable with break

    Setting running = False does not exit the loop immediately. The loop finishes the current iteration, then checks the condition. If running is False, the loop exits on the next check. This is different from break, which exits right away.

    Fix: Use break if you want to exit immediately. Use running = False if you want to exit after the current iteration completes.

Comparing break and continue

Aspectbreakcontinue
What it doesExits the loop immediatelySkips the rest of the current iteration
Execution after the statementJumps to the first statement after the loopJumps back to the loop condition check
Does the else-block run?No, the else-block is skippedYes, if the loop exits normally after continue
Does the loop repeat?No, the loop is doneYes, if the condition is still True
Common use caseExit early when a target is found or an error occursSkip invalid or unwanted input and continue processing

Practice: Predicting Loop Behavior

What do you think happens?

A while loop has a condition running = True. Inside the loop, if a certain condition is met, break executes. After the loop, there is an else-block that prints 'Loop completed normally.' Will this message print?

  • Yes, the else-block always runs after a loop.
  • No, break skips the else-block.
  • Only if the loop runs more than once.
  • Only if the condition is checked more than once.
Reveal answer

Answer: No, break skips the else-block.

When break executes, the loop exits immediately and the else-block is skipped entirely. The else-block only runs if the loop condition becomes False naturally (without break). So the message 'Loop completed normally' will not print.

Practice: Identifying break vs. continue

MEDIUM

For each scenario, decide whether you should use break or continue (or neither). Explain your choice. 1. You are reading numbers from the user. When the user enters -1, you want to stop the loop and move on to the next part of the program. 2. You are reading numbers from the user. When the user enters a negative number, you want to skip it and ask for the next number, but keep the loop running. 3. You are looping through a list of items. When you find the item you are looking for, you want to stop searching and use that item. 4. You are looping through a list of items. When you encounter an item you do not want to process, you want to skip it and move to the next item in the list.

Hints
  • Think about whether you want to exit the loop completely or just skip the current iteration.
  • Remember that break exits immediately and skips the else-block, while continue jumps back to the condition check.
  • Ask yourself: do I want to stop the loop, or do I want to skip this iteration and keep going?

Summary

Loop control statements break and continue give you precise control over how a loop executes. break exits the loop immediately, skipping any remaining iterations and the else-block. continue skips the rest of the current iteration and jumps back to the condition check, allowing the loop to continue if the condition is still True. Understanding the difference between these two statements—and knowing when the else-block runs—is essential for writing loops that behave exactly as you intend. Use break when you want to stop the loop early. Use continue when you want to skip the current iteration but keep looping. Use the else-block to run code only when the loop completes normally (without break).

Key Takeaways

  • break exits a loop immediately and skips the else-block; execution jumps to the first statement after the loop.
  • continue skips the rest of the current iteration and jumps back to the loop condition check; the loop may continue if the condition is still True.
  • The else-block runs only when the loop condition becomes False naturally; break prevents the else-block from running.
  • Use break to exit early when a target is found or an error occurs; use continue to skip unwanted iterations and keep looping.
  • Proper indentation is essential: break and continue must be inside the loop body, not at the same level as the while statement.