1. for Loop
Meaning: Kisi sequence ke har element ke liye ek kaam baar-baar karna.
Syntax:
for variable in sequence:
# do something
Example:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
apple
banana
mango
2. range() with for Loop
range() number series banata hai. Last value exclusive hoti hai.
for i in range(1, 6):
print(i)
1
2
3
4
5
3. Common Mistakes in for Loop
for i in 5:
print(i) # ❌ 5 is not iterable
for i in range(5):
print(i) # ✅ Correct
4. while Loop
Meaning: Jab tak condition true hai, tab tak loop chalega.
count = 1
while count <= 5:
print(count)
count += 1
1
2
3
4
5
5. Infinite Loop Mistake
while True:
print("Infinite loop") # ❌ No stop condition
6. break Statement
Meaning: Loop ko turant band kar deta hai.
for i in range(1, 6):
if i == 3:
break
print(i)
1
2
7. continue Statement
Meaning: Current iteration skip karta hai, agla chalu kar deta hai.
for i in range(1, 6):
if i == 3:
continue
print(i)
1
2
4
5
8. else with Loops
Meaning: Agar loop break nahi hota to else
part run hota hai.
for i in range(3):
print(i)
else:
print("Loop done")
0
1
2
Loop done
9. else skipped when break used
for i in range(3):
if i == 1:
break
print(i)
else:
print("Loop done")
0
10. Nested Loops
Meaning: Ek loop ke andar doosra loop (jaise table banate ho).
for i in range(1, 4):
for j in range(1, 3):
print(f"{i} x {j} = {i*j}")
1 x 1 = 1
1 x 2 = 2
2 x 1 = 2
2 x 2 = 4
3 x 1 = 3
3 x 2 = 6