Introduction to Loops
Loops in Python are used to repeat a block of code multiple times.
Instead of writing the same code again and again, we use loops to make programs short, simple, and efficient.
Real-Life Example
Loops are like daily activities:
- Brushing teeth every day
- Counting numbers
- Repeating homework practice
Why Loops are Important
Loops are important because they help programmers:
- avoid repeated code
- automate tasks
- process large amounts of data
- improve program efficiency
- build real-world applications
Types of Loops in Python

1. for Loop
The for loop is used to repeat code a fixed number of times.
It is commonly used when we know how many times we want to repeat something.
Example
for i in range(5):
print(i)
Output
0
1
2
3
4
The loop runs 5 times
2. while Loop
The while loop is used to repeat code until a condition becomes False
It is used when we don’t know how many times the loop will run.
Example
x = 0
while x < 5:
print(x)
x += 1
Output
0
1
2
3
4
Loop runs until x < 5 becomes False
Difference Between for and while
| for loop | while loop |
|---|---|
| Fixed number of times | Runs based on condition |
| Easy to use | Needs condition control |
| Used with range() | Used with condition |
How Loops Work
Step 1
Python checks the loop condition.
Step 2
If condition is True:
-
loop block executes
Step 3
Python again checks the condition.
Step 4
The process repeats until the condition becomes False.
Common Beginner Mistakes
- Infinite loop in while
- Wrong indentation
- Forgetting to update variable
- Wrong range values
Advantages of Loops
- Reduces code repetition
- Makes code shorter
- Improves readability
- Saves development time
- Handles repetitive tasks easily
➤ Summary
-
Loop statements in Python are used to repeat tasks automatically.
Python mainly provides two types of loops:
- for loop
- while loop
Loops help programmers:
- reduce repeated code
- automate tasks
- improve efficiency
- build real-world applications