In Python, the break
and continue
statements are used to control the flow of a loop.
The break
statement is used to exit a loop prematurely if a certain condition is met. When the break
statement is encountered inside a loop, the loop is immediately terminated and the program execution resumes at the next statement after the loop. Here’s an example of how to use the break
statement in a while
loop:
x = 0 while x < 10: print(x) x += 1 if x == 5: break
In this example, the while
loop will iterate 10 times, but the break
statement is used to terminate the loop prematurely when x
equals 5. The output of this code will be:
0 1 2 3 4
The continue
statement, on the other hand, is used to skip over the rest of the code in a loop for a particular iteration if a certain condition is met. When the continue
statement is encountered inside a loop, the current iteration of the loop is terminated, and the program execution resumes with the next iteration of the loop. Here’s an example of how to use the continue
statement in a for
loop:
for i in range(10): if i % 2 == 0: continue print(i)
In this example, the for
loop will iterate over the range of numbers from 0 to 9. When i
is even (i.e., i
modulus 2 equals 0), the if
statement is true, and the continue
statement is executed, causing the loop to skip over the print
statement for that particular iteration. Therefore, the output of this code will be:
1 3 5 7 9
Both break
and continue
statements are useful tools for controlling the flow of loops in Python. However, it’s important to use them judiciously to avoid creating code that is difficult to understand or maintain.