Loops allow a program to perform a repetitive task efficiently. Python has two primary loop constructs: the while loop and the for loop.
1. The while Loop
The while loop executes a block of code as long as a specified Boolean condition remains True.
- Initialization: Requires a loop control variable to be set before the loop starts.
- Condition: The loop continues as long as this condition is met.
- Update: The loop control variable must be changed inside the loop to eventually make the condition
False, preventing an infinite loop.
# Initialization
count = 1
# Condition: Loop continues as long as count <= 5
while count <= 5:
print(count)
# Update: Increment count to move towards the exit condition
count = count + 1
print("Loop finished!")
2. The for Loop
The for loop is used to iterate over a sequence (like a list, string, or tuple) or any iterable object. It is Python’s most common loop type.
A. Iterating Over a Sequence
The loop automatically steps through each item in the sequence.
fruits = ["apple", "banana", "cherry"]
# The variable 'fruit' takes the value of each item in the list sequentially
for fruit in fruits:
print(f"I like {fruit}.")
B. Iterating with range()
The built-in range() function generates a sequence of numbers, which is often used in a for loop when you need a specific number of iterations.
| Syntax | Description | Sequence Generated |
range(stop) | Numbers starting from 0, up to (but not including) stop. | range(3) $\rightarrow$ 0, 1, 2 |
range(start, stop) | Numbers from start up to (but not including) stop. | range(2, 5) $\rightarrow$ 2, 3, 4 |
range(start, stop, step) | Numbers with a specified increment/decrement value. | range(0, 10, 2) $\rightarrow$ 0, 2, 4, 6, 8 |
# Loop 5 times (0, 1, 2, 3, 4)
for i in range(5):
print(f"Iteration {i}")
3. Loop Control Statements
These statements allow you to alter the normal execution flow of a loop.
A. The break Statement
The break statement immediately terminates the current loop entirely, regardless of the loop condition, and execution jumps to the statement following the loop.
items = ["A", "B", "STOP", "C"]
for item in items:
if item == "STOP":
break # Exit the loop immediately
print(item)
# Output: A, B (C is never reached)
B. The continue Statement
The continue statement immediately skips the rest of the code in the current iteration of the loop and moves to the next iteration.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0: # If number is even
continue # Skip the print statement for this number
print(num)
# Output: 1, 3, 5 (Only odd numbers are printed)
4. The else Clause with Loops
Python uniquely allows an else block to be attached to both for and while loops.
- The
elseblock executes only if the loop finishes without encountering abreakstatement.
found = False
for i in range(5):
if i == 10:
found = True
break
else:
# This block executes because the loop completed naturally (i != 10)
print("Item not found in the loop range.")
