In Python, loops are used to execute a block of code repeatedly.
The two main types of loops
are:
🔹 1. For Loop
Used to iterate over a sequence (like a list, tuple, string, or range).
✅ Syntax:
python
CopyEdit
for variable in sequence:
# code block
✅ Example 1: Using range()
python
CopyEdit
for i in range(5):
print(i)
# Output: 0 1 2 3 4
✅ Example 2: Iterating over a list
python
CopyEdit
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
🔹 2. While Loop
Repeats a block of code as long as a condition is True.
✅ Syntax:
python
CopyEdit
while condition:
# code block
✅ Example:
python
CopyEdit
count = 0
while count < 5:
print(count)
count += 1
# Output: 0 1 2 3 4
🔸 Loop Control Statements
These are used to control the flow inside loops:
Statement Description
break Exits the loop immediately
continue Skips the current iteration
pass Does nothing (placeholder)
✅ Example using break:
python
CopyEdit
for i in range(5):
if i == 3:
break
print(i)
# Output: 0 1 2
✅ Example using continue:
python
CopyEdit
for i in range(5):
if i == 3:
continue
print(i)
# Output: 0 1 2 4
Let me know if you'd like this content converted into a downloadable PDF once the tools are
working again.