Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. This helps in automating repetitive tasks and iterating over collections of data. Python provides two primary types of loops: `for` loops and `while` loops.
1. `for` Loop:
The `for` loop is used for iterating over a sequence (that is, a list, tuple, dictionary, set, or string) or other iterable objects. It executes a block of code once for each item in the sequence.
- Syntax:
```python
for item in sequence:
code to be executed for each item
```
- How it works: The loop variable (`item` in the syntax) takes on the value of each element in the `sequence` one by one, and the indented block of code is executed for each value. A common use case is with the `range()` function to loop a specific number of times, like `for i in range(5):` which loops 5 times (i from 0 to 4).
2. `while` Loop:
The `while` loop is used to execute a block of code repeatedly as long as a specified condition is true. The loop continues to run until the condition becomes false.
- Syntax:
```python
while condition:
code to be executed as long as the condition is True
(ensure condition eventually becomes False to avoid infinite loops)
```
- How it works: Before each iteration, the `condition` is evaluated. If it's `True`, the code block inside the loop is executed. After the block runs, the condition is evaluated again. If it's `False`, the loop terminates. It's crucial to ensure that something within the loop's code block eventually changes a variable involved in the condition, making the condition `False`, otherwise, you'll create an infinite loop.
Control Statements:
- `break`: Terminates the loop entirely and execution continues at the statement immediately following the loop.
- `continue`: Skips the rest of the current iteration of the loop and proceeds to the next iteration (or re-evaluates the condition in a `while` loop).
Example Code
Example for 'for' loop: Iterating over a list
print("--- For Loop Example ---")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Example for 'for' loop with range()
print("\n--- For Loop with range() Example ---")
for i in range(3): Loops 3 times (0, 1, 2)
print(f"Counting: {i + 1}")
Example for 'while' loop: Countdown
print("\n--- While Loop Example ---")
count = 3
while count > 0:
print(f"Countdown: {count}")
count -= 1 Decrement count to eventually make the condition False
print("Blast off!")
Example combining while loop with user input and 'break'
print("\n--- While Loop with User Input and Break ---")
while True: Infinite loop until 'break' is encountered
user_input = input("Enter 'quit' to exit: ").lower()
if user_input == 'quit':
print("Exiting the loop.")
break Exit the while loop
else:
print(f"You entered: {user_input}")
Example for 'continue' in a for loop
print("\n--- For Loop with Continue ---")
numbers = [1, 2, 3, 4, 5, 6]
print("Even numbers:")
for num in numbers:
if num % 2 != 0: If the number is odd
continue Skip the rest of this iteration
print(num) Only prints even numbers








Loops (for, while)