Python Loop Control: How to Use the break Statement to Stop Processing

When using for or while loops, you may want to stop the loop immediately if a specific error occurs or if you find the data you were looking for. To achieve this “escape from the loop,” Python uses the break statement.

This article explains how to use the break statement to forcibly terminate a loop when a specific condition is met.


目次

Basic Behavior of the break Statement

When the break statement is executed, the Python interpreter immediately interrupts the currently running loop (the innermost loop) and moves to the next process outside the loop block. This is effective when there is no need to repeat anymore or when continuing would cause problems.


Specific Example: Emergency Stop by Detecting Abnormal Values

As an example, let’s create a program that checks a list of temperature data obtained from factory sensors in order. If data exceeding the allowable range (threshold) is found, it is an abnormal situation, so it is necessary to stop checking the remaining data and immediately stop the system (terminate the loop).

# List of temperature data obtained from sensors
sensor_temperatures = [45.2, 48.5, 52.0, 115.8, 47.0, 46.5]

# Safety limit temperature
safety_limit = 100.0

print("--- Start Temperature Check ---")

for temp in sensor_temperatures:
    # Check if it exceeds the limit temperature
    if temp > safety_limit:
        print(f"WARNING: Abnormal temperature {temp} degrees detected.")
        print("System Emergency Stop.")
        # Force terminate the loop here
        break
    
    # Process for normal case
    print(f"Checking... {temp} degrees: Normal")

print("--- Check Process Finished ---")

Output:

--- Start Temperature Check ---
Checking... 45.2 degrees: Normal
Checking... 48.5 degrees: Normal
Checking... 52.0 degrees: Normal
WARNING: Abnormal temperature 115.8 degrees detected.
System Emergency Stop.
--- Check Process Finished ---

Explanation

The list elements 45.2, 48.5, and 52.0 do not exceed the safety_limit (100.0), so the if condition is False, and the “Normal” message is displayed. The 4th element, 115.8, exceeds the limit, so the program enters the if block. After displaying the warning message, the break statement is executed. As a result, although 47.0 and 46.5 remain in the list, they are not processed, and the entire loop ends.


Application in Search Processing

The break statement is often used not only for error handling but also for “searching.” The logic is “If the data you are looking for is found, there is no need to search further, so finish.”

# User ID list
user_ids = ["u001", "u005", "u003", "u008"]
target_id = "u003"

for uid in user_ids:
    if uid == target_id:
        print(f"Target ID {target_id} found.")
        break
    print(f"Checking {uid}...")

Output:

Checking u001...
Checking u005...
Target ID u003 found.

Once u003 was found, the loop stopped, and unnecessary processing (checking u008) was skipped.


Summary

  • Use the break statement to forcibly terminate a loop midway.
  • By combining it with an if statement, you can control the loop to “stop if an abnormal value is found” or “finish if the target value is found.”
  • When break is executed, processing for the remaining elements is skipped.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次