Control Flow
if
if x > 5:
Use when a single condition needs to be checked, like validating input.
Executes code conditionally based on a true/false condition
Can be verbose with multiple conditions
elif
elif x == 10:
Useful for multiple conditions, like checking a range of values or status codes.
Provides an alternative condition if the previous if
is false
Can become complex if not organized well
else
else: print("x is not greater than 5")
Use when you need a fallback for all other conditions.
Executes code if no other condition is true
Can be confusing if overused or misused
while
while x < 10:
Use for repeated actions as long as a condition is met (e.g., reading from a file until EOF).
Loops until a condition is no longer true
Risk of infinite loops if condition isn't correctly defined
for
for i in range(5):
Ideal for iterating over sequences, like lists or ranges.
Iterates over a sequence (list, tuple, string)
Limited to iterable objects; needs specific iteration conditions
break
if x == 5: break
Use to exit a loop early, e.g., when a condition is met.
Exits the nearest loop
Can be misused and make code harder to read
continue
if x == 5: continue
Use to skip specific iterations based on a condition (e.g., skipping certain numbers in a loop).
Skips to the next iteration in a loop
Can make the code flow harder to follow if overused
pass
if x > 5: pass
Use when a block of code is syntactically required but no action is needed (e.g., during development or in empty functions).
Placeholder for code that is syntactically required but not yet implemented
Doesn't perform any action
Last updated