DEV Community

Cover image for Controlling Loops with break and continue
Sharon-nyabuto
Sharon-nyabuto

Posted on

Controlling Loops with break and continue

Knowing when to stop or skip a loop in Python

In our last article we saw how we can efficiently repeat processes with for and while loops.
But what if we do not want our loop going all the way? How can we tell Python to stop a loop early or skip a single iteration, without ending the entire program?

The break statement

Loops are important, but sometimes we do not want every iteration to execute. This is where the break statement is helpful.
The break statement immediately terminates a loop. Once Python encounters break it exits the loop and goes on to execute the rest of the program.

Syntax:

for item in sequence:
    if condition:
        break
Enter fullscreen mode Exit fullscreen mode

For example:

respondents = ["R001", "R002", "R003", "R004", "R005","R006","R007","R008"]

for respondent in respondents:
    if respondent == "R005":
        print("Respondent found!")
        break
    print(f"Checking respondents : {respondent}")
Enter fullscreen mode Exit fullscreen mode

Here is what happens step by step:

  1. Python starts the for loop and assigns the first value, "R001", to the variable respondent.

  2. It checks whether respondent == "R005", and since "R001" is not equal to "R005", the condition is False.

  3. Python skips the break statement and executes print("Checking", respondent), displaying:

       Checking respondents: R001
    
  4. The loop repeats for "R002" all through "R004", and since none of those are still ==R005, Checking respondent is still printed.

  5. On the next iteration, respondent becomes "R005". This time, the condition respondent == "R005"evaluates to True. Python prints:

        Respondent found!
    
  6. The break statement is executed, causing Python to immediately exit the loop. The remaining items, "R006" through "R008", are never processed. The output therefore becomes:

        Checking respondents : R001
        Checking respondents : R002
        Checking respondents : R003
        Checking respondents : R004
        Respondent found!
    

It is important to note that the break statement does not stop the entire program, it only stops the current loop. Python proceeds to execute the next tines of code after the loop.

Here are a few more examples;

Example 1:

# Q1. A school bus can carry 30 students. Students keep boarding one by one. Stop boarding as soon as the bus is full. Print how many are on board after each student boards.

capacity = 30
students = 0

while True:
    students += 1
    capacity -= 1

    print(f"Students aboard: {students} | Seats left: {capacity}")

    if capacity == 0:
        break 

# The break statement provides the loop with an exit condition by terminating it as soon as capacity reaches 0. Otherwise it would keep running infinitely beyond 0.
Enter fullscreen mode Exit fullscreen mode

Result:

Students aboard: 1 | Seats left: 29
Students aboard: 2 | Seats left: 28
Students aboard: 3 | Seats left: 27
....
Students aboard: 28 | Seats left: 2
Students aboard: 29 | Seats left: 1
Students aboard: 30 | Seats left: 0
Enter fullscreen mode Exit fullscreen mode

Example 2:

#Q2:  A car park has 20 spaces. Cars keep arriving one by one. Ask if a car wants to park. If yes, reduce spaces by 1. Stop when the car park is full. Show spaces remaining after each car.

spaces = 20
cars_parked = 0

while True:
    car_parking = input("Do you want to park? (yes/no): ")

    if car_parking.lower() == "yes":
        cars_parked += 1
        spaces -= 1
        print("Go ahead and park.")
        print(f"Cars parked: {cars_parked}")
        print(f"Spaces left: {spaces}\n")

        if spaces == 0:
            print("The car park is now full.")
            break
    else:
        print("Thank you. Have a good day!")
        break
Enter fullscreen mode Exit fullscreen mode

These are just two examples of where break could be used. Other situations that would require break include:

  1. Stop searching once a specific respondent ID is found.
  2. Exit a password prompt after the correct password is entered.
  3. Stop processing transactions once the daily limit has been reached.
  4. End a quiz when the user chooses to quit.

The continue statement

We've seen that thebreakstatement terminates a loop as soon as a specified condition is met. The continue statement behaves differently. Instead of ending the loop, it skips the rest of the current iteration and immediately moves on to the next one, without terminating the loop.

Syntax:

for item in sequence:
    if condition:
        continue
Enter fullscreen mode Exit fullscreen mode

To better understand the difference between break and continue, let's use the same initial example from the break section.
Notice how changing one statement will affect the behavior of the loop.

respondents = ["R001", "R002", "R003", "R004", "R005","R006","R007","R008"]

for respondent in respondents:
    if respondent == "R005":
        continue
    print(f"Checking respondents : {respondent}")
Enter fullscreen mode Exit fullscreen mode

Here is what happens step by step:

  1. Python starts the for loop and assigns the first value, "R001", to the variable respondent.
  2. It checks whether respondent == "R005". Since "R001" is not equal to "R005", the condition evaluates to False.
    Python skips the continue statement and executes:

    print(f"Checking respondent: {respondent}")
    

    displaying:

    Checking respondent: R001
    
  3. The same process repeats for "R002", "R003", and "R004", with each respondent being printed.

  4. On the next iteration, respondent becomes "R005". This time, the condition respondent == "R005" evaluates to True.

  5. Python executes the continue statement, immediately skipping the print() statement for this iteration. As a result, "R005" is NOT displayed.

  6. Instead of ending the loop, Python moves directly to the next iteration and continues processing "R006", "R007", and "R008" until all respondents have been checked.

  7. The output therefore becomes;

    Checking respondents : R001
    Checking respondents : R002
    Checking respondents : R003
    Checking respondents : R004
    Checking respondents : R006
    Checking respondents : R007
    Checking respondents : R008
    

    As you will see from the output, the continue statement skips only the current iteration, which in our case is "R005", then proceeds with the remaining iterations until there are no more items to process.

Here are a few more examples;

#Scenario 1: A customer wants to withdraw money from an ATM. If they enter an amount greater than their account balance, ask them to enter another amount instead of ending the transaction.

balance = 10000

while True:
    amount = int(input("Enter withdrawal amount: "))
    if amount > balance:
        print("Insufficient balance.\n")
        continue

    balance -= amount
    print(f"Successfully withdrawn Kshs. {amount}. New balance: Ksh {balance}")
    break
Enter fullscreen mode Exit fullscreen mode
#Scenario 2: Imagine you're analysing a survey dataset containing household incomes. Respondents who didnt disclose income are marked as -1. How can we skip these missing values while continuing to analyse the rest of the dataset?
household_ids = ["HH001", "HH002", "HH003", "HH004", "HH005", "HH006", "HH007"]
household_incomes = [25000, 18000, -1, 32000, 15000, -1, 27000]

for i in range(len(household_ids)):
    if household_incomes[i] == -1:
        continue

    print(f"{household_ids[i]} | Income: Ksh {household_incomes[i]}")
Enter fullscreen mode Exit fullscreen mode

These are just two examples of where continue could be used. Other situations that would require continue include:

  1. Ignoring duplicate records when cleaning a dataset.
  2. Skipping products that are out of stock while processing customer orders.
  3. Ignoring files with an unsupported format when processing multiple files in a folder.
  4. Skipping weekends and holidays when generating a work schedule or calculating business days.

Conclusion

At the beginning of the article we asked ; How can we tell Python to stop a loop early or skip a single iteration, without ending the entire program?

We've now seen how the break and continue statements give us control over loops. While break allows us to exit a loop as soon as a condition is met, continue lets us skip the current iteration and move on to the next one. Together, they help us write programs that are efficient, flexible and more managable.

As always, don't stop with the examples in this article. Modify them, experiment with different scenarios, and challenge yourself to find other situations where break and continue can simplify your code.

What's next?

So far, we've learned how to control a single loop. But what happens when one loop isn't enough?

In the next article, we'll answer that question as we explore nested loops.

Top comments (0)