Python_Loops_Presentation (1)
Python_Loops_Presentation (1)
• Output:
• apple
• banana
• cherry
while Loop Syntax
• Syntax:
• while condition:
• # code block
• 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.