Iteration means repeating a block of code multiple times. In Python, this is done using loops. Loops are used to implement the repetition construct in algorithms.
Without loops, you would have to write the same statement many times. Loops allow you to:
for LoopA for loop is used to iterate over a sequence (such as a range of numbers, a list, or a string) a fixed number of times.
for variable in sequence:
# body of loop
range()The range() function generates a sequence of numbers.
| Function Call | Sequence Generated |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 10, 2) | 0, 2, 4, 6, 8 |
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
total = 0
for i in range(1, 11):
total = total + i
print("Sum =", total)
Output: Sum = 55
while LoopA while loop repeats a block of code as long as a condition remains True. It is used when the number of repetitions is not known in advance.
while condition:
# body of loop
count = 1
while count <= 5:
print(count)
count = count + 1
Output:
1
2
3
4
5
⚠️ Infinite Loop Warning: If the condition never becomes False, the loop runs forever. Always make sure the loop variable is updated inside the loop body.
break and continue StatementsbreakExits the loop immediately, even if the condition is still True.
for i in range(1, 10):
if i == 5:
break
print(i)
# Output: 1 2 3 4
continueSkips the current iteration and moves to the next one.
for i in range(1, 6):
if i == 3:
continue
print(i)
# Output: 1 2 4 5
A loop inside another loop is called a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop.
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()
Output:
1 2 3
2 4 6
3 6 9
for vs while| Feature | for Loop | while Loop |
|---|---|---|
| Use when | Number of iterations is known | Condition-based repetition |
| Iterates over | Sequences, ranges | Any boolean condition |
| Risk of infinite loop | Low | High if condition not updated |
Algorithm: Find the sum of all even numbers from 1 to 20.
Pseudocode:
sum ← 0
FOR i FROM 1 TO 20
IF i MOD 2 = 0 THEN
sum ← sum + i
PRINT sum
Python Code:
sum = 0
for i in range(1, 21):
if i % 2 == 0:
sum = sum + i
print("Sum of even numbers:", sum)
Output: Sum of even numbers: 110
| Term | Meaning |
|---|---|
| Iteration | Repeating a block of code |
| Loop | A control structure that repeats code |
range() | Built-in function to generate a number sequence |
| Infinite loop | A loop that never terminates |
| Nested loop | A loop inside another loop |
break | Exits the loop immediately |
continue | Skips current iteration and goes to next |