Python 3 – break statement
The break statement is an important feature in Python 3 that allows us to exit out of a loop prematurely. It’s a control statement that can be used to terminate the loop in which it is executed. We can use the break statement in a for loop or a while loop. In this article, we will be discussing how to use the break statement in Python 3 with simple and easy-to-understand examples.
How the break statement works?
When the break statement is executed in a loop, it causes the loop to immediately terminate and jump to the next statement after the loop. The break statement only has an effect when it is executed inside a loop. If the break is executed outside of the loop, it will result in an error.
Here’s a simple syntax for using the break statement:
while test_expression:
statement(s)
if condition:
break
In the above code, the while loop is executed as long as the test_expression
evaluates to true. The statement(s)
inside the loop are executed repeatedly until the conditional condition
is true. At this point, the break statement is executed and the loop is immediately terminated.
Examples
Now let’s dive into some examples of how to use the break statement in Python 3.
Example 1: Using break in a while loop
Let’s say we want to print out numbers from 1 to 5, but we want to stop printing once we reach the number 3. We can use the break statement to exit the loop prematurely.
Here’s the code for achieving that:
x = 1
while x <= 5:
print(x)
if x == 3:
break
x += 1
Output:
1
2
3
In the above code, we first initialize x
with the value of 1. Then we use a while loop to print out numbers from 1 to 5. We use an if statement inside the loop to check whether x
is equal to 3. If it is, we execute the break statement, which immediately terminates the loop.
Example 2: Using break in a for loop
Now let’s take a look at an example using the break statement in a for loop. Let’s say we have a list of numbers and we want to print them out until we reach a negative number. We can use the break statement to exit the loop.
Here’s the code for achieving that:
numbers = [1, 2, 3, 4, -5, 6, 7, 8, 9, 10]
for num in numbers:
if num < 0:
break
print(num)
Output:
1
2
3
4
In the above code, we define a list of numbers and use a for loop to iterate through each item in the list. We use an if statement inside the loop to check whether the current number is negative. If it is, we execute the break statement, which immediately terminates the loop.
Conclusion
The break statement is an important control statement in Python 3 that allows us to exit out of a loop prematurely. We can use it in both for loops and while loops. When executed, the break statement immediately terminates the loop and jumps to the next statement after the loop. It’s a handy tool for optimizing loops and streamlining code. We hope this article has been helpful in explaining how to use the break statement in Python 3 with easy-to-understand examples.