What is a Loop?
A loop is used to repeat the same block of code multiple times without writing it again and again.
Why Loops?
- To reduce repeated code
- To perform tasks multiple times easily
- To save time and effort
Types of Loops in Python
- while loop – condition based loop
- for loop – sequence based loop
while Loop
- Runs while a condition is True
- Condition is checked before every iteration
- Loop variable must be updated
for Loop
- Used when number of repetitions is known
- Mostly used with range()
range() Function
- range(5) → generates 0 to 4
- range(1, 6) → generates 1 to 5
- range(2, 11, 2) → generates even numbers
- Stop value is always excluded
break Statement
Used to stop the loop completely.
continue Statement
Used to skip the current iteration.
pass Statement
Used as a placeholder. It does nothing.
Infinite Loop
Happens when loop condition never becomes False.
Key Points
- Use for loop when count is known
- Use while loop when condition is unknown
- Indentation is very important in loops
Now attempt the quiz below.
Day 4 Quiz – Loops
Select the correct answer and click Submit to see your score.
0 Comments