Loops are used to execute a block of code repeatedly as long as a condition is true or until a specific number of times.
🧠 Types of Loops in Python:
forloopwhileloop- Nested loops
loop control statements–break,continue,pass
1️⃣ for Loop
✅ Definition:
The for loop is used for iterating over a sequence (like a list, tuple, dictionary, string, or range).
🔹 Syntax:
for variable in sequence:
# code block✅ Example 1: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)✅ Example 2: Use with range()
for i in range(5):
print(i)
// Output: 0 1 2 3 42️⃣ while Loop
✅ Definition:
The while loop executes a block of code as long as the condition is True.
🔹 Syntax:
while condition:
# code block✅ Example:
i = 1
while i <= 5:
print(i)
i += 13️⃣ Nested Loops
✅ Definition:
A loop inside another loop.
✅ Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")🔃 Loop Control Statements
➤ break
Used to exit the loop early.
for i in range(10):
if i == 5:
break
print(i)➤ continue
Skips the current iteration.
for i in range(5):
if i == 2:
continue
print(i)➤ pass
Does nothing (used as a placeholder).
for i in range(3):
pass # Just a placeholder🔂 Loop with else
✅ else with for or while:
Executes only if the loop is not terminated by break.
for i in range(3):
print(i)
else:
print("Finished without break.")🔍 Real-World Example: Sum of Even Numbers
sum = 0
for i in range(1, 11):
if i % 2 == 0:
sum += i
print("Sum of even numbers:", sum)🔁 Summary Table:
| Loop Type | When to Use | Can Use Else? | Control Statements |
|---|---|---|---|
for | Iterating over sequences | ✅ Yes | break, continue, pass |
while | When the number of iterations is unknown | ✅ Yes | break, continue, pass |
| Nested | Complex patterns (grids, matrices) | ✅ Yes | break, continue, pass |
