In Python, the keywords break and continue are utilized exclusively within loops. The main purpose of these statements is to terminate the execution of a loop and to skip to the next iteration, respectively.
In this Python tutorial, we will explore the break and continue statements, including their applications. Following that, we will examine the distinctions between these two concepts.
What is the break Statement in Python?
In Python, the break statement serves to terminate a loop before its condition evaluates to false or before completing the iteration over all elements. When the break statement is triggered, control exits the loop instantly, and the program proceeds to execute the first statement that follows the loop.
Let us see a few examples of the break statement.
Example 1: Searching in a List
In this instance, we will explore the application of a break statement within a 'for' loop to halt the iteration as soon as a specific item is located in the provided list.
Example
# given list
fruits = ['apple', 'mango', 'guava', 'banana', 'grapes']
target_fruit = 'guava'
# iterating through the given list
for fruit in fruits:
if fruit == target_fruit:
print(f"{target_fruit} found in the list!")
# using break statement
break
print("Checking:", fruit)
else:
print(f"{target_fruit} not found in the list!!")
Output:
Checking: apple
Checking: mango
guava found in the list!
Explanation:
In this scenario, we are provided with a collection of elements. Additionally, we are tasked with locating a specific element within this collection. To achieve this, we utilize a 'for' loop to iterate through the elements of the list. Within this loop, an if-statement is employed to determine if the current element matches the desired element, and the break statement is used to stop any further iterations once the element is located. Furthermore, an else-block is included with the 'for' loop to display a different message if the element is not found.
Example 2: Exiting a User Input Loop
In this illustration, we will explore the utilization of a break statement within a 'while' loop to end the loop when the user inputs 'exit'.
Example
# using the while loop
while True:
# asking user to input something
user_input = input("Enter something (type 'exit' to quit): ")
if user_input == "exit":
print("Exiting the loop.")
# using break statement
break
print(f"You entered: {user_input}")
Output:
Enter something (type 'exit' to quit): hello
You entered: hello
Enter something (type 'exit' to quit): welcome to
You entered: welcome to
Enter something (type 'exit' to quit): logicpractice tech
You entered: logicpractice tech
Enter something (type 'exit' to quit): exit
Exiting the loop.
Explanation:
In this example, the input function is utilized within a 'while' loop to continuously prompt the user to input text indefinitely. We then employ a break statement in conjunction with an if-statement to end the loop when the user types 'exit'.
What is the continue Statement in Python?
In Python, the continue statement is utilized within for or while loops to bypass the rest of the code for the current iteration and promptly proceed to the next iteration.
In contrast to break, which terminates the entire loop, continue allows the loop to persist. It merely bypasses the execution of one iteration of the loop when a defined condition is met, subsequently continuing with the normal execution of the loop for the following item or value.
Next, we will examine a few illustrations of the continue statement.
Example 1: Skipping Numbers divisible by 3
Let's examine an example to grasp how the continue statement functions within a 'for' loop to bypass numbers that are divisible by 3.
Example
# using the for loop
for num in range(1, 13):
if num % 3 == 0:
# skipping if the current number is divisible by 3
continue
print("Counting:", num)
Output:
Counting: 1
Counting: 2
Counting: 4
Counting: 5
Counting: 7
Counting: 8
Counting: 10
Counting: 11
Explanation:
In this instance, we utilized a 'for' loop to iterate through the numbers from 1 to 13. Within this loop, we assessed whether the current number is divisible by 3 and employed the continue statement to bypass that iteration.
Example 2: Skipping a Specific Character in a string
In Python, the continue statement allows us to bypass a specific character in a string. Here is a straightforward example demonstrating the functionality of continue within a 'while' loop.
Example
# given string
msg = "logicpractice tech"
# intializing counter
i = 0
# using the while loop
while i < len(msg):
if msg[i] == 't':
# incrementing the value of i
i += 1
# skipping the current iteration
continue
print(msg[i])
# incrementing the value of i
i += 1
Output:
p
o
i
n
e
c
h
Explanation:
In this scenario, a string has been provided. A counter has been set to 0, and a while loop is employed to traverse the characters within the string. Within the if-block, the continue statement is utilized to bypass a specific character in the provided string.
Key Differences between Break and Continue
We will now look at the key differences between the break and continue statements in Python.
| Feature | break | continue |
|---|---|---|
| Basic Function | Terminates the loop entirely. | Skips the current iteration and proceeds with the next. |
| Loop Behavior | Exits the loop immediately when condition is met. | Skips remaining code in current loop iteration. |
| Effect on Loop | Stops the loop. | Does not stop the loop-continues to next iteration. |
| Control Flow | Jumps out of the loop block. | Jumps to the beginning of the next iteration. |
| Usage Scenario | When you want to stop a loop prematurely. | When you want to skip certain values or conditions. |
| Code Execution After Statement | Does not execute remaining code in the loop after break. Loop ends. | Does not execute remaining code in current iteration, but loop continues. |
| Loop Type Used In | Works with both for and while loops. | Also works with both for and while loops. |
| Common Use Cases | Searching for an itemExiting menu loopsBreaking infinite loops | Skipping unwanted valuesIgnoring errorsFiltering data |
- Searching for an item
- Exiting menu loops
- Breaking infinite loops
- Skipping unwanted values
- Ignoring errors
- Filtering data
- break terminates the loop entirely, so no further iterations are executed.
- continue does not conduct the current iteration but proceeds to the following iteration of the loop.
Difference between Break and Continue in Python FAQs
1. What is the primary distinction between break and continue in Python?
2. When should we apply break in Python?
Utilizing a break statement is recommended when a specific condition arises that necessitates the premature exit of a loop. For example, if a particular value is identified in a list, and subsequent iterations are unnecessary.
3. When should we use continue in Python?
The recommendation is to utilize continue when the goal is to bypass the current loop iteration and proceed to the subsequent one. For instance, this is applicable when there is a desire to omit certain values from processing, such as None values present in a list.
4. What occurs to the code following break in a loop?
Once the break statement is executed, the loop can no longer continue its execution. The code that follows the break within the loop will not be executed before the code that comes after the break statement.
5. What happens to the code following continue in a loop?
Upon encountering the continue statement within a loop, the remaining code following the continue for the current iteration is bypassed, and the loop advances directly to the subsequent iteration. Nonetheless, any code preceding the continue statement in the loop is executed as expected.