In Python, loops (for
and while
) allow you to execute a block of code multiple times. To control the flow of these loops, Python provides two useful keywords: break
and continue
. These keywords allow you to alter the normal flow of loops by either terminating the loop prematurely or skipping certain iterations.
break
Keyword in PythonThe break
keyword is used to exit a loop immediately, regardless of whether the loop has finished iterating through all elements. Once break
is encountered, the loop terminates, and the control moves to the next statement following the loop.
break
in a for
LoopOutput:
The loop prints numbers from 1 to 4. When the value of num
reaches 5, the break
statement is executed, and the loop terminates, skipping the rest of the numbers.
break
in a while
LoopOutput:
The loop stops when i
equals 7, exiting the loop due to the break
statement.
continue
Keyword in PythonThe continue
keyword is used to skip the current iteration of the loop and move directly to the next one. Unlike break
, it doesn’t terminate the entire loop but simply bypasses the remaining code in the current iteration and continues with the next.
continue
in a for
LoopOutput:
The loop skips printing the number 3 by using the continue
statement and continues with the next iterations.
continue
in a while
LoopOutput:
The loop skips the iteration where i
equals 2, but continues to print the other numbers.
break
and continue
break
: Exits the loop entirely, stopping further iterations.continue
: Skips the current iteration and continues with the next iteration of the loop.break
and continue
If you're searching for a specific item in a list and want to stop once it is found, you can use the break
keyword.
Output:
If you want to process all elements in a list except for specific values, you can use the continue
keyword.
Output:
This loop skips even numbers and only prints odd numbers.
The break
and continue
keywords in Python are powerful tools for controlling the flow of loops. The break
keyword allows you to exit a loop when a certain condition is met, while continue
enables you to skip an iteration and move to the next one. By using these keywords effectively, you can manage loop execution more efficiently and handle various conditions within your loops.