Python break and continue

The break and continue statements let us exit loops early or skip iterations as needed, giving us more ways to control loop execution.


Python break Statement

The break statement terminates the loop immediately when it's encountered.

Syntax

break

The break statement is usually used with an if...else statement. This is because if break is used directly, the loop would stop immediately on its first iteration, making the loop pointless.


Example: break in for Loop

number = int(input("Enter a number: "))
for i in range(1, 6):

    # Terminate the loop if i equals number
    if i == number:
        break
    print(i)

Output

Enter a number: 3
1
2

In the program, the loop is supposed to iterate from i = 1 to 5.

However, if the user enters 3, the loop only prints 1 and 2. When i becomes 3, the if condition is met, so the break statement terminates the loop before it completes all iterations.

Click the Visualize button above to see how this program works, step by step.


Example: break in while Loop

while True:
    number = int(input("Enter a number: "))
    if number < 0:
        break
    print(f"You entered {number}")

Output

Enter a number: 5
You entered 5
Enter a number: 0
You entered 0
Enter a number: -2

In the program, True is directly used as the loop condition. The only way to terminate such infinite loops is by using a break statement.

When the user enters a negative number, the if condition is met and the break statement terminates the loop.

Click the Visualize button above to see how this program works, step by step.


Python continue Statement

The continue statement ends the current iteration and continues with the next iteration.

Basically, continue skips the remaining code in the current iteration. The loop doesn't terminate; it simply moves on to the next iteration.

Syntax

continue

Similar to break, the continue statement is usually used with an if...else statement. This is because if continue is used directly, the remaining code in the loop body would be skipped on every iteration.


Example: continue in for Loop

for i in range(1, 11):

    # Condition to check if a number is even
    if i % 2 == 0:
        continue
    print(i)

Output

1
3
5
7
9

In the program, the loop iterates from i = 1 to 10. The if condition, i % 2 == 0, is True when i is even. In this case, the print() statement is skipped and the loop continues with the next iteration. That's why only odd numbers are printed.


Example: Sum of Only Positive Numbers

In this example, we'll create a program to find the sum of positive numbers entered by the user.

If the user enters a negative number, we'll skip adding it to the total using continue. And if the user enters 0, we'll terminate the loop using break and display the sum.

total = 0

while True:
    number = int(input("Enter a number (0 to stop): "))

    # Skip negative numbers
    if number < 0:
        continue

    # End the loop if the user enters 0
    if number == 0:
        break

    total += number

print(f"Sum of positive numbers: {total}")

If you're having trouble following this program, you can always click the Visualize button to see how the program works step by step.


Loop with else Clause

The for and while loops in Python can have an optional else clause. This feature is unique to Python and is not found in most other languages.

The code inside the else clause is executed after all iterations are complete. However, if the loop is terminated by using a break statement, the else block will not be executed.

stock = ['Laptop', 'Keyboard', 'Mouse']

order = input("Enter the product you want to buy: ")

for product in stock:
    if product == order:
        print(f"{order} is available. Adding to cart.")
        break
else:
    print(f"Sorry, {order} is out of stock.")

Output 1

Enter the product you want to buy: Laptop
Laptop is available. Adding to cart.

Output 2

Enter the product you want to buy: Monitor
Sorry, Monitor is out of stock.

The logic here is:

  • If the product is in stock, the break statement terminates the loop and the out of stock message inside else is not displayed.
  • If the product is not in stock, the out of stock message is displayed, as the break statement is never encountered.

Again, if you're having trouble following this program, you can always click the Visualize button to see how the program works step by step.

Did you find this article helpful?