covering both for and while loops:
Syntax:
for variable in iterable:
# Code to be repeated
Iterable:
Range Function:
range() to iterate over a sequence of numbers.for i in range(start, stop, step):
# Code to be repeated
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Else Clause:
else block can be used to execute code after the loop without a break statement.for variable in iterable:
# Code to be repeated
else:
# Code after the loop (optional)
Syntax:
while condition:
# Code to be repeated
Condition:
True.Example:
count = 0
while count < 5:
print(count)
count += 1
Break and Continue:
break: Exits the loop prematurely.continue: Skips the rest of the code inside the loop for the current iteration.while condition:
if some_condition:
break # exit the loop
# other code
Else Clause:
for loops, else block is executed after the loop unless a break statement is encountered.while condition:
# Code to be repeated
else:
# Code after the loop (optional)
Nested Loops:
for and while loops can be nested (placed inside each other).for i in range(3):
for j in range(2):
print(i, j)
Loop Control:
pass: Do nothing (used as a placeholder).pass is also useful when a loop is syntactically required but you want to skip its execution temporarily.for variable in iterable:
pass # placeholder, no operation
Understanding these concepts will help you effectively use for and while loops in Python for various tasks.