A loop is used to repeat a block of code multiple times.
for
loopUsed to iterate over a sequence like a list, tuple, string, or range.
for i in range(5):
print(i)
✅ Output: 0 1 2 3 4
✨ Tip: range(start, stop, step)
is often used.
while
loopRepeats as long as a condition is True.
count = 0
while count < 5:
print(count)
count += 1
✅ Output: 0 1 2 3 4
nested
loopA loop inside another loop.
for i in range(2):
for j in range(3):
print(i, j)
✅ Output:
0 0
0 1
0 2
1 0
1 1
1 2
Keyword | Purpose |
---|---|
break |
Exits the loop completely 🚪 |
continue |
Skips the current iteration 🔁 |
pass |
Does nothing, just a placeholder 🧱 |
for i in range(5):
if i == 3:
break
print(i)
✅ Output: 0 1 2
for i in range(5):
if i == 3:
continue
print(i)
✅ Output: 0 1 2 4
Use Case | Loop Type |
---|---|
Know how many times to loop | for loop |
Loop until condition is met | while loop |
Iterate over a sequence | for loop |
Start 🔹
↓
[ Condition? ]
↓ Yes ↓ No
[ Execute Block ] → End 🔚
↓
Repeat 🔁