Using the break statement in Python
In Python, the break statement is used to terminate a loop prematurely. When the break statement is encountered inside a loop, the loop is immediately terminated and control is transferred to the statement immediately following the loop.
Syntax
The syntax for the break statement in Python is as follows:
while expression:
statement(s)
if condition:
break
or:
for variable in sequence:
statement(s)
if condition:
break
Here,
expression
is a Boolean expression that determines whether the loop should continue,
statement(s)
is the body of the loop, and
condition
is a Boolean expression that determines whether to terminate the loop prematurely.
Example
Let's look at an example of using the break statement to terminate a loop:
# Program to find the first even number in a list
numbers = [3, 7, 12, 6, 8, 9]
for num in numbers:
if num % 2 == 0:
print("The first even number in the list is:", num)
break
In this example, we have a list of numbers and we want to find the first even number in the list. We use a for loop to iterate over each number in the list, and we use an if statement to check if the current number is even. If it is, we print a message and then use the break statement to terminate the loop prematurely.
Conclusion
The break statement is a useful tool for terminating loops prematurely in Python. By using the break statement, you can write more concise and readable code that is easier to understand and maintain.