Google News
logo
Python Program to Using the break statement in a for loop
In the following example of Python program that demonstrates how to use the `break` statement in a `for` loop :
Program :
# Using the break statement in a for loop
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)
    if number == 3:
        break

print("Done.")
Output :
1
2
3
Done.
In this program, we use a `for` loop to iterate over a list of numbers. Inside the loop, we use the `print()` function to print each number in the list.

We also use an `if` statement to check if the current number is equal to `3`. If it is, we use the `break` statement to exit the loop immediately.

When the loop exits, the program continues to execute the `print()` statement outside the loop, which prints the message "Done."

You can use the `break` statement to exit a loop prematurely based on a condition. In this example, we exit the loop as soon as we encounter the number `3`.