Iteration means repeating a block of code. Instead of writing the same code multiple times, we use a loop to execute it repeatedly. Python has two main loop types: for loops (count-controlled) and while loops (condition-controlled).
A for loop repeats a set number of times. It iterates over a sequence (like a range of numbers or items in a list).
range() function:
| Syntax | What it produces | Example |
|---|---|---|
range(n) | 0, 1, 2, ... n-1 | range(5) → 0, 1, 2, 3, 4 |
range(start, stop) | start, start+1, ... stop-1 | range(1, 6) → 1, 2, 3, 4, 5 |
range(start, stop, step) | start, start+step, ... up to stop | range(0, 10, 2) → 0, 2, 4, 6, 8 |
A while loop repeats as long as a condition remains True. The number of iterations is not fixed — it depends on when the condition becomes False.
| for loop | while loop |
|---|---|
| Use when you know how many times to repeat | Use when you repeat until a condition is met |
| Iterating over a list or range | Input validation (repeat until valid input) |
| Processing each element of a collection | Game loops (repeat until player loses) |
| Counting (1 to 10) | Searching (repeat until found) |
| Always terminates (given finite range/list) | Risk of infinite loop if condition never becomes False |
A loop inside another loop is called a nested loop. The inner loop completes all its iterations for every single iteration of the outer loop.
| Keyword | Effect | Example |
|---|---|---|
| break | Immediately exits the loop entirely | Search a list and stop when item is found |
| continue | Skips the rest of the current iteration and goes to the next | Skip even numbers, only process odd |
range(1, 10) produces 1–9, not 1–10. To include 10, use range(1, 11)8 questions
num = int(input("Enter a number (1-10): "))
while num < 1 or num > 10:
print("Invalid! Try again.")
num = int(input("Enter a number (1-10): "))
print("Valid number:", num)Mark: getting input before the loop [1]; while condition checks both boundaries (num<1 or num>10) [1]; print error message inside loop [1]; get input again inside loop (essential — otherwise infinite loop) [1].for i in range(1, 11):
print("7 x", i, "=", 7 * i)Mark: correct for loop syntax with range [1]; range(1, 11) to include 10 [1]; correct multiplication 7*i [1]; print statement showing the multiplication [1]. Output: 7 x 1 = 7, 7 x 2 = 14, ..., 7 x 10 = 70.| Term | Definition |
|---|
10 minutes · Exam-style