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 Use Loops?
- Saves time and effort
- Reduces repeated code
- Makes programs efficient
- Helps in solving problems easily
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 |
Common Beginner Mistakes
- Infinite loop in while
- Wrong indentation
- Forgetting to update variable
- Wrong range values
➤ Key Points
Loopsrepeat code multiple times- for loop → fixed repetitions
- while loop → condition-based
- Helps reduce code length
- Improves logic building
➤ Tips
- Use for loop when count is known
- Use while loop when condition is needed
- Avoid infinite loops
- Practice with small examples