Python Loops
Understanding Python's Iterative
Structures
What are Loops?
• Loops in Python allow you to repeat a block of
code multiple times.
• Two main types of loops:
• 1. **for loop**
• 2. **while loop**
for Loop Syntax
• Syntax:
• for variable in iterable:
• # code block
• The for loop iterates over an iterable (e.g., list,
tuple, string) and executes a block of code for
each item in the iterable.
for Loop Example
• Example:
• fruits = ['apple', 'banana', 'cherry']
• for fruit in fruits:
• print(fruit)
• Output:
• apple
• banana
• cherry
while Loop Syntax
• Syntax:
• while condition:
• # code block
• The while loop continues executing the block
of code as long as the condition remains True.
while Loop Example
• Example:
• counter = 5
• while counter > 0:
• print(counter)
• counter -= 1
• Output:
• 5
• 4
• 3
• 2
• 1
break and continue
• 1. **break**: Exits the loop entirely.
• 2. **continue**: Skips the rest of the code inside the loop for the current
iteration.
• Example (break):
• for i in range(5):
• if i == 3:
• break
• print(i)
• Example (continue):
• for i in range(5):
• if i == 3:
• continue
• print(i)
Nested Loops
• A nested loop is a loop inside another loop.
• Example:
• for i in range(3):
• for j in range(2):
• print(f'i={i}, j={j}')
• Output
• i=0, j=0
• i=0, j=1
• i=1, j=0
• i=1, j=1
• i=2, j=0
• i=2, j=1
Conclusion
• Loops are an essential part of programming,
allowing repetitive tasks to be performed
efficiently. Mastering both for and while loops,
as well as understanding break and continue,
will help you write more effective code.