
Python
Loops solve one of programming's most fundamental problems: how do you repeat code without copying and pasting?
Imagine you need to print "Hello!" 5 times. Without loops, you'd do this:
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")Problems:
With a loop, the same task becomes:
for i in range(5):
print("Hello!")Benefits:
Example 1: Processing student grades
# Without loops - impossible to scale
grade1 = 85
grade2 = 90
grade3 = 78
average = (grade1 + grade2 + grade3) / 3
# With loops - handles any number of grades
grades = [85, 90, 78, 92, 88]
total = 0
for grade in grades:
total = total + grade
average = total / len(grades)Example 2: Building a multiplication table
# With loops - clean and elegant
for i in range(1, 13):
for j in range(1, 13):
print(f"{i} × {j} = {i*j}")| Scenario | Without Loops | With Loops |
|---|---|---|
| Summing 10 numbers | 10 lines | 3 lines |
| Processing 1000 rows of data | Impossible | 2-3 lines |
| Printing a grid pattern | 100+ lines | 5 lines |
| Reading a file | Repeat manually | 2 lines |
Python provides two main types:
1. For Loop — When you know exactly how many times to repeat
```python
for i in range(5):
print(i) # Runs 5 times
```
2. While Loop — When you repeat until a condition is met
```python
while count < 5:
print(count)
count = count + 1
```
| Concept | Remember |
|---|---|
| DRY Principle | Don't Repeat Yourself — use loops instead |
| Scalability | Loops work with any repetition count |
| Readability | Loops make code easier to understand |
| Efficiency | Loops are much faster than manual repetition |
| Foundation | Loops are essential for working with data |
Master For Loops Basics to start writing your first loops!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward