In Python, break, continue, and pass are keywords that are used to control the flow of a program.
Here’s a brief explanation of each one, along with examples:
break: The break keyword is used to exit a loop early, before the loop condition is met. It can be used in both while and for loops.
for i in range(10): if i == 5: break print(i)
This will output:
0 1 2 3 4
As soon as the condition i == 5 gets true, the loop will be break.
continue: The continue keyword is used to skip the current iteration of a loop and move on to the next one. It can also be used in both while and for loops.
for i in range(10): if i % 2 == 0: continue print(i)
This will output:
1 3 5 7 9
As soon as the condition i % 2 == 0 gets true, the current iteration will be skipped and it will move on to the next iteration.
pass: The pass keyword is used as a placeholder when there is no code to execute in a specific block of a program. It is often used as a placeholder when defining a function or a class, but not yet implementing its behavior.
for i in range(10): if i == 5: pass else: print(i)
This will output:
0 1 2 3 4 6 7 8 9
As soon as the condition i == 5 gets true, the pass statement will be executed, which does nothing and continues to next iteration.