In Python, break
and continue
are two control flow statements that are used to alter the behavior of loops, such as for
and while
loops.
break
statement: The break
statement is used to terminate the execution of a loop prematurely. When the interpreter encounters a break
statement within a loop, it immediately exits the loop and resumes execution at the next statement after the loop. This can be useful when you want to terminate a loop early based on some condition. Here is an example:
for i in range(10):
if i == 5:
break
print(i)
In this example, the loop will iterate from 0 to 9, but when i
reaches 5, the break
statement will be executed, and the loop will terminate prematurely. The output of this code will be:
0
1
2
3
4
continue
statement: The continue
statement is used to skip over the current iteration of a loop and move on to the next iteration. When the interpreter encounters a continue
statement within a loop, it skips the rest of the current iteration and jumps back to the beginning of the loop to start the next iteration. This can be useful when you want to skip over certain items in a loop based on some condition. Here is an example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
In this example, the loop will iterate from 0 to 9, but when i
is even, the continue
statement will be executed, and the rest of the code within the loop will be skipped for that iteration. The output of this code will be:
1
3
5
7
9
I hope this helps you understand the use of break
and continue
in Python!