📘 Coding – Day 6: Introduction to
Loops (For and While Loops)
🧠 Why Loops?
Loops help us execute a block of code multiple times without writing it again and again.
🔄 Types of Loops in Python
1. For Loop – Used when you know how many times to repeat.
2. While Loop – Used when repetition depends on a condition.
✅ 1. For Loop – Syntax:
python
Copy code
for i in range(5):
print(i)
🔍 Explanation:
range(5) gives: 0, 1, 2, 3, 4
i takes each value one by one
Output:
Copy code
📌 Range Variants
python
Copy code
range(start, stop) # from start to stop-1
range(start, stop, step) # step can skip numbers
Example:
python
Copy code
for i in range(2, 10, 2):
print(i)
# Output: 2, 4, 6, 8
✅ 2. While Loop – Syntax:
python
Copy code
i=0
while i < 5:
print(i)
i += 1
🔍 Explanation:
Starts from 0
Checks condition before every run
Increments by 1 each time
⚠️ Be Careful: Infinite Loops
python
Copy code
while True:
print("This runs forever")
Use break inside loop to stop it.
🔁 Loop Control Statements
break → exits the loop
continue → skips to next iteration
pass → does nothing (used as a placeholder)
Example:
python
Copy code
for i in range(5):
if i == 3:
continue
print(i)
# Output: 0, 1, 2, 4
🧠 Practice Problems:
1. Print all even numbers from 1 to 20.
2. Write a while loop to print "Hello" 10 times.
3. Use a for loop to calculate the sum of first 10 natural numbers.
4. Print multiplication table of 5 using a for loop.
✅ Summary:
Topic Description
for loop Repeats using range/sequence
while loop Repeats while condition true
break Stops the loop
continue Skips current iteration