Day 6: Loops in Python
Loops are one of the most powerful concepts in programming. They allow you to execute code repeatedly, automate tasks, and handle large data efficiently.
In today’s session, we’ll cover:
- For Loop
- While Loop
- Break & Continue
- Loop Else Concept (Important & Unique to Python)
Why Loops Matter?
Imagine:
- Printing numbers from 1 to 100
- Processing thousands of users
- Running a condition until it's satisfied
Without loops → repetitive code ❌
With loops → clean & efficient code ✅
FOR LOOP
What is a For Loop?
A for loop is used to iterate over a sequence (list, string, tuple, etc.).
Syntax
for variable in iterable:
# code block
How It Works
- Takes one element at a time from iterable
- Assigns it to variable
- Executes the block
- Repeats until iterable ends
Example
for i in range(5):
print(i)
Output:
0
1
2
3
4
Understanding range()
range(start, stop, step)
Examples:
range(5) # 0 to 4
range(1, 5) # 1 to 4
range(1, 10, 2) # 1, 3, 5, 7, 9
Looping Through Data Types
String
for ch in "Python":
print(ch)
List
for num in [10, 20, 30]:
print(num)
FOR-ELSE (Important Concept)
for i in range(3):
print(i)
else:
print("Loop completed")
else runs only if loop doesn't break
WHILE LOOP
What is a While Loop?
Executes code as long as condition is True
Syntax
while condition:
# code block
Example
i = 0
while i < 5:
print(i)
i += 1
Infinite Loop
while True:
print("Running...")
Runs forever unless stopped manually
WHILE-ELSE
i = 0
while i < 3:
print(i)
i += 1
else:
print("Done")
Runs only if loop ends normally (no break)
BREAK STATEMENT
Stops loop immediately
for i in range(5):
if i == 3:
break
print(i)
CONTINUE STATEMENT
Skips current iteration
for i in range(5):
if i == 2:
continue
print(i)
FOR vs WHILE
| Feature | For Loop | While Loop |
|---|---|---|
| Based on | Iterable | Condition |
| Use Case | Known iterations | Unknown iterations |
| Risk | Safe | Can become infinite |
Key Takeaways
- for loop → iterate over data
- while loop → run until condition fails
- break → stops loop
- continue → skips iteration
- else → runs only if loop completes normally
Practice Questions
Basic
- Print numbers from 1 to 10 using for loop
- Print numbers from 10 to 1 using while loop
- Print all characters in a string
- Print even numbers from 1 to 20
Intermediate
- Sum of first n numbers
- Multiplication table of a number
- Count digits in a number
- Reverse a number
Advanced
- Check if number is prime (use loop + break + else)
- Fibonacci series
- Pattern printing (triangle)
- Menu-driven program using while loop
.png)

.png)
