Python Loops
Python loops are used to execute a block of code repeatedly. There are two primary types of loops in Python:
for
loopwhile
loop
Why Use Loops?
Loops help reduce code repetition by allowing a block of code to run multiple times under a condition. You use them when you want to iterate over sequences (lists, strings, tuples, dictionaries, sets) or repeat a task until a condition is met.
Python for
Loop
The for
loop is used to iterate over a sequence.
Syntax:
for variable in sequence:
# code block
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
You can also use range()
with a for
loop:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Python while
Loop
The while
loop runs as long as a condition is True
.
Syntax:
while condition:
# code block
Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Loop Control Statements
Python provides control statements to modify loop behavior.
1. break
– Exit the loop:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
2. continue
– Skip to the next iteration:
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
3. pass
– Do nothing (placeholder):
for i in range(3):
pass # Used when the loop is required syntactically but no action is needed
Nested Loops
You can place one loop inside another.
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
else
with Loops
Python allows an optional else
clause after loops, which executes when the loop ends normally (no break
).
for i in range(3):
print(i)
else:
print("Loop completed!")
Output:
0
1
2
Loop completed!
Loop Exercises
Try solving these:
- Print numbers from 1 to 10 using a
while
loop. - Print even numbers between 1 and 20 using a
for
loop. - Use a
for
loop to iterate through a dictionary and print key-value pairs. - Use nested loops to print a pattern like:
Summary
Loop Type | Description |
---|---|
for | Iterates over a sequence |
while | Runs while condition is true |
break | Exits the loop early |
continue | Skips current iteration |
pass | Placeholder, does nothing |
else | Executes if loop ends normally |