Break
The break
and continue
statements are used to control the flow of execution in a loop in Python.
The break
statement is used to terminate a loop prematurely. When a break
statement is encountered inside a loop, the loop is immediately terminated, and the control is transferred to the first statement after the loop. Here's an example that uses the break
statement to find the first even number in a list:
numbers = [1, 3, 5, 2, 4, 6]
for number in numbers:
if number % 2 == 0:
print(f"The first even number is {number}")
break
In this example, the for
loop iterates over the numbers
list, and the if
statement inside the loop checks if the current number is even. If an even number is found, the break
statement is executed to terminate the loop, and the message indicating the first even number is printed.
Continue
The continue
statement is used to skip the current iteration of a loop, and move on to the next iteration. When a continue
statement is encountered inside a loop, the rest of the code in the current iteration is skipped, and the control is immediately transferred to the next iteration. Here's an example that uses the continue
statement to print only the odd numbers in a list:
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0:
continue
print(number)
In this example, the for
loop iterates over the numbers
list, and the if
statement inside the loop checks if the current number is even. If the number is even, the continue
statement is executed to skip the current iteration and move on to the next iteration. If the number is odd, the rest of the code in the current iteration is executed, and the number is printed.