π Loops in Python
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 |
No comments yet! You be the first to comment.
