Skip to content

Python stop for loop

In Python, you can stop a for loop prematurely using the break statement. The break statement is used to exit the loop immediately when a certain condition is met. Once the break statement is encountered, the loop terminates, and the program continues with the next statement after the loop.

Here’s the general syntax of using break within a for loop:

for item in iterable:
    # Code inside the loop
    if condition:
        break  # Exit the loop if the condition is met
    # Code continues if the condition is not met
  • item: This is a variable that takes on each item of the iterable in each iteration of the loop. You can choose any valid variable name to represent each item in the iterable.
  • iterable: This is the collection over which the loop iterates. It can be a list, tuple, string, dictionary, or any other iterable object.
  • condition: This is the expression that you want to check at each iteration. If the condition evaluates to True, the break statement will be executed, and the loop will terminate immediately.
  • break: This keyword is used to exit the loop when the specified condition is met. Once the break statement is executed, the loop stops, and the program continues with the next statement after the loop.

Python stop for loop example

Here’s a practical example of using the break statement to stop a for loop:

Let’s say we have a list of numbers, and we want to find the first even number in the list. Once we find an even number, we’ll stop the loop and print the result.

numbers = [23, 14, 17, 6, 31, 12, 9, 8]

for num in numbers:
    if num % 2 == 0:  # Check if the number is even
        print(f"Found the first even number: {num}")
        break
else:
    print("No even number found in the list.")

Output:

Python stop for loop

Another example

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target_value = 7

for num in numbers:
    if num == target_value:
        print(f"Found the target value {target_value}!")
        break
    print(num)

In this example, the loop will stop when it encounters the value 7. If the target value is not found in the list, the loop will continue until it reaches the end of the iterable.

With String

fruits = ["apple", "banana", "orange", "grape", "pear"]

for fruit in fruits:
    if fruit == "orange":
        print("Found the orange!")
        break

print("Loop is done.")

In this example, the loop iterates through the list of fruits. When it encounters the string “orange”, the break statement is executed, and the loop is terminated immediately.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *