Loops allow executing a block of code multiple times, reducing repetition and improving efficiency. Python provides for
and while
loops, along with loop control statements.
1. The for Loop
A for
loop is used to iterate over a sequence (list, tuple, string, dictionary, or range).
Syntax:
for variable in sequence:
# Code block to execute in each iteration
Example: Iterating through a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Using range() in for Loops
The range()
function generates a sequence of numbers.
for i in range(5):
print(i) # Output: 0 1 2 3 4
Looping with a custom start and step:
for i in range(2, 10, 2):
print(i) # Output: 2 4 6 8
2. The while Loop
A while
loop executes as long as a condition remains True
.
Syntax:
while condition:
# Code block executed while condition is True
Example:
x = 5
while x > 0:
print(x)
x -= 1 # Decrement x
Output:
5
4
3
2
1
3. Loop Control Statements
Loop control statements modify loop execution.
3.1 break Statement
Terminates the loop prematurely.
for num in range(10):
if num == 5:
break # Exit loop when num is 5
print(num)
Output:
0
1
2
3
4
3.2 continue Statement
Skips the current iteration and moves to the next one.
for num in range(5):
if num == 2:
continue # Skip when num is 2
print(num)
Output:
0
1
3
4
3.3 pass Statement
Acts as a placeholder for future code.
for i in range(5):
if i == 3:
pass # Placeholder for future implementation
print(i)
4. Nested Loops
Loops can be nested inside other loops.
Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
5. The else Clause in Loops
Python allows an else
clause with loops, which executes when the loop completes normally (without break
).
Example:
for num in range(5):
print(num)
else:
print("Loop finished!")
Output:
0
1
2
3
4
Loop finished!
Summary
✅ for loops iterate over sequences.
✅ while loops execute based on conditions.
✅ break
exits loops early, while continue
skips an iteration.
✅ Nested loops allow complex iterations.
✅ else with loops runs after a successful loop completion.