Member-only story
The break
, continue
, and pass
keywords are used to control the flow of a program, especially within loops and conditional statements.
break
:
break
is used to exit a loop prematurely when a certain condition is met.- It is commonly used in
for
andwhile
loops to terminate the loop before it completes all iterations.
for i in range(1, 6):
if i == 3:
break # This will exit the loop when i is 3
print(i)
#output = 1 2
continue
:
continue
is used to skip the current iteration of a loop and proceed to the next one.- It is typically used when you want to skip specific iterations based on a condition.
for i in range(1, 6):
if i == 3:
continue # This will skip iteration when i is 3
print(i)
#output 1 2 4 5
pass
:
pass
is a null operation statement in Python, used as a placeholder when syntactically some code is required but you don't want it to do anything.- It is often used when defining classes, functions, or conditional statements that you plan to implement later.
for i in range(1, 6):
if i == 3:
pass # This doesn't do anything when i is 3
else:
print(i)
# output: 1 2 4 5
These keywords are valuable for controlling the flow of our code and handling different situations within loops and conditional blocks.