Python break and continue
break
and continue
are two control flow statements in Python that allow you to change the behavior of loops.
break
statement is used to exit a loop prematurely. When a break
statement is executed inside a loop, the loop is immediately terminated and the program execution continues with the next statement following the loop.
Here's an example of using break
statement in a while loop that prints numbers from 1 to 5, but breaks out of the loop when the number 3 is reached:
i = 1 while i <= 5: print(i) if i == 3: break i += 1
Output:
1 2 3
In this example, the break
statement is executed when the value of i
is 3. The loop is then immediately terminated and the program execution continues with the next statement after the loop.
continue
statement is used to skip the current iteration of a loop and move to the next iteration. When a continue
statement is executed inside a loop, the loop immediately goes to the next iteration, skipping the remaining statements in the current iteration.
Here's an example of using continue
statement in a while loop that prints only odd numbers from 1 to 5:
i = 1 while i <= 5: if i % 2 == 0: i += 1 continue print(i) i += 1
Output:
1 3 5
In this example, the continue
statement is executed when the value of i
is even. The loop then immediately goes to the next iteration and skips the print
statement, resulting in only odd numbers being printed to the console.