for LoopIterates over the elements of an iterable (like lists, tuples, strings, ranges). Used when you know how many times you want to loop or are processing items in a collection.
for variable in iterable:
# Code to execute for each item in the iterable
statement_1
statement_2
# ...
variable: A temporary variable that takes on the value of each element in the iterable during each loop iteration.iterable: An object that can be iterated over.iterable.while LoopExecutes a block of code repeatedly as long as a condition is true. Used when the number of iterations is not known beforehand.
while condition:
# Code to execute while condition is True
statement_a
statement_b
# ...
condition: An expression that evaluates to True or False. The loop continues as long as this condition remains True.condition eventually becomes False to avoid an infinite loop.condition is True.These statements change the flow of execution within loops.
break: Exits the innermost for or while loop immediately.
while True:
# ... code ...
if exit_condition:
break # Stop the loop
continue: Skips the rest of the current loop iteration and moves to the next one.
for item in my_list:
if skip_condition:
continue # Skip to the next item
# ... rest of loop code ...
pass: Does nothing. Used as a placeholder where a statement is syntactically required but no code is needed.
for item in another_list:
if condition_to_ignore:
pass # Do nothing for this item
else:
# ... process other items ...
pass