Computer ScienceChapter 3: Programming Fundamentals (Python)
3.9 Iteration & Loop
Iteration
Explanation level
Introduction
In programming, we often need to repeat the same task multiple times. For example, displaying a message five times, calculating the sum of the first ten numbers, or processing each item in a list. Writing the same code over and over again would be inefficient and error-prone. Python provides loops to handle repetition automatically.
Definition
Iteration is the process of repeating a set of instructions multiple times.
A loop is a programming construct that allows a block of code to be executed repeatedly based on a condition or for a specified number of times.
In simple words, a loop lets you repeat code without writing it again and again.
Main Idea
Computer programs are the most useful in daily life where the same task is to be executed in an iterative fashion. Rather than write code for every part of the same iteration, we incorporate iterations in the programming language to write small code for iterations and execute effectively.
The most commonly used loop in Python is the for loop.
Core Concept
- Starting point — where the loop begins
- Terminating condition — when the loop stops
- Step size — how much the index changes each time
The loop will execute the instruction(s) for the defined range.
Detailed Explanation
The for Loop
For example, you want to display your name five times. Rather than writing the `print()` function five times, a better alternative is to place the `print()` function once within the for loop and define the range to be five.
Example — Print Name Five Times: ```python for i in range(5): print(i, '-- Computer Science !!!') ```
Output: ``` 0 -- Computer Science !!! 1 -- Computer Science !!! 2 -- Computer Science !!! 3 -- Computer Science !!! 4 -- Computer Science !!! ```
- `range(5)` generates numbers from 0 to 4 (5 numbers, not including 5)
- The loop runs 5 times
- `i` takes the values 0, 1, 2, 3, 4 in each iteration
The range() Function
The `range()` function is used to define the sequence of numbers for the loop.
Syntax: ```python range(stop) range(start, stop) range(start, stop, step) ```
Examples:
| Code | Generates | Number of values |
|---|---|---|
| `range(5)` | 0, 1, 2, 3, 4 | 5 |
| `range(1, 5)` | 1, 2, 3, 4 | 4 |
| `range(11, 15)` | 11, 12, 13, 14 | 4 |
| `range(10, 20, 2)` | 10, 12, 14, 16, 18 | 5 |
| `range(5, 0, -1)` | 5, 4, 3, 2, 1 | 5 |
Custom Range — Start, Stop, Step
The program in the following example starts the loop index from 11, terminating value is provided to be 15 with a step-size of 1.
Example — Custom Range: ```python for i in range(11, 15, 1): print(i, '-- Computer Science !!!') ```
Output: ``` 11 -- Computer Science !!! 12 -- Computer Science !!! 13 -- Computer Science !!! 14 -- Computer Science !!! ```
Important: The terminating value is not inclusive. So `range(11, 15)` gives 11, 12, 13, 14 — not 15.
Step Size
When the terminating condition in a loop is met, the loop stops. In other words, the value we provide for the terminating condition of the loop is not inclusive. As far as the step-size is concerned, we can provide any non-zero value, according to which the index value will update itself.
Example — Step Size of 2: ```python for i in range(10, 20, 2): print(i, '-- Computer Science !!!') ```
Output: ``` 10 -- Computer Science !!! 12 -- Computer Science !!! 14 -- Computer Science !!! 16 -- Computer Science !!! 18 -- Computer Science !!! ```
Example — Negative Step Size: ```python for i in range(10, 0, -1): print(i, '-- Computer Science !!!') ```
Output: ``` 10 -- Computer Science !!! 9 -- Computer Science !!! 8 -- Computer Science !!! 7 -- Computer Science !!! 6 -- Computer Science !!! 5 -- Computer Science !!! 4 -- Computer Science !!! 3 -- Computer Science !!! 2 -- Computer Science !!! 1 -- Computer Science !!! ```
For the sake of practice, you may explore for-loops further, by assigning a negative value to step-size, in range function. Thus, for any series and sequence, the value of range can be set accordingly.
Indentation in Python
Here another important aspect to note is the indentation of the code. Indentation:
- Provides better readability and visibility of the code as the lines of code increases
- Helps outline the composition of the code and ultimately the overall program
It is quite critical to follow the 'indentation rules' in Python, as the line/lines of code if not correctly indented can result in logical bugs and unforeseen outcomes of the program.
The `:` after the for loop statement shows that the lines of code that follow are to be executed in the loop; and hence need to be indented for the understanding of Python interpreter.
Correct Indentation: ```python for i in range(5): print(i) # Indented — inside the loop print("Done") # Not indented — outside the loop ```
Incorrect Indentation: ```python for i in range(5): print(i) # This causes an error ```
Practical Examples with for Loop
Example 1 — Sum of First 10 Positive Numbers: ```python sum = 0 for i in range(10): sum = sum + (i + 1) print('The sum of first ten positive numbers is:', sum) ```
Output: ``` The sum of first ten positive numbers is: 55 ```
- `sum = 0` — Initialize sum to 0
- `range(10)` — Loop runs 10 times with i = 0, 1, 2, ..., 9
- `sum = sum + (i + 1)` — Adds 1, 2, 3, ..., 10 to sum
- Final sum = 55
Example 2 — Multiplication Table: ```python num = eval(input("Enter a number: ")) for i in range(1, 11): print(num, 'x', i, '=', num * i) ```
Output: ``` Enter a number: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 ```
Example 3 — Print Squares of Numbers: ```python for i in range(5): print((i+1), '** 2 =', (i+1) ** 2) ```
Output: ``` 1 ** 2 = 1 2 ** 2 = 4 3 ** 2 = 9 4 ** 2 = 16 5 ** 2 = 25 ```
The while Loop
Python also provides a `while` loop, which repeats as long as a condition is true.
Syntax: ```python while condition: # code to repeat ```
Example — Sum Using while Loop: ```python i = 1 total = 0 while i <= 10: total = total + i i = i + 1 print("Sum:", total) ```
Output: ``` Sum: 55 ```
Important: In a while loop, you must update the variable in the condition, otherwise the loop will run forever (infinite loop).
for Loop vs while Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Use when | Number of iterations is known | Number of iterations is not known |
| Condition | Built into range() | Checked at the start of each iteration |
| Initialization | Automatic | Manual |
| Increment | Automatic (step size) | Manual |
| Risk of infinite loop | Low | High (if not careful) |
Intermediate Level
The range() Function — Detailed
The `range()` function can take 1, 2, or 3 arguments:
- Starts at 0, ends at stop-1
- Step size is 1
- Example: `range(5)` → 0, 1, 2, 3, 4
- Starts at start, ends at stop-1
- Step size is 1
- Example: `range(2, 6)` → 2, 3, 4, 5
- Starts at start, ends at stop-1
- Step size is step
- Example: `range(1, 10, 2)` → 1, 3, 5, 7, 9
- `range(10, 0, -1)` → 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- `range(10, 0, -2)` → 10, 8, 6, 4, 2
Common Patterns with for Loop
Pattern 1 — Sum of Numbers: ```python total = 0 for i in range(1, 11): total = total + i print(total) # 55 ```
Pattern 2 — Product of Numbers: ```python product = 1 for i in range(1, 6): product = product * i print(product) # 120 ```
Pattern 3 — Count Even Numbers: ```python count = 0 for i in range(1, 21): if i % 2 == 0: count = count + 1 print("Even numbers from 1 to 20:", count) # 10 ```
Pattern 4 — Print Multiplication Table: ```python num = 7 for i in range(1, 11): print(num, 'x', i, '=', num * i) ```
Nested Loops
You can put one loop inside another.
Example — Multiplication Table for 1 to 3: ```python for i in range(1, 4): for j in range(1, 4): print(i, 'x', j, '=', i * j) print() # Empty line between tables ```
**Output:** ``` 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 ```
The else with for Loop
Python allows an optional `else` block with a for loop. The `else` block executes when the loop completes normally (without a `break`).
Example: ```python for i in range(3): print(i) else: print("Loop finished") ```
Output: ``` 0 1 2 Loop finished ```
The break Statement
The `break` statement exits the loop immediately.
Example: ```python for i in range(10): if i == 5: break print(i) ```
Output: ``` 0 1 2 3 4 ```
The continue Statement
The `continue` statement skips the rest of the code in the current iteration and moves to the next.
Example: ```python for i in range(5): if i == 2: print(i) ```
Output: ``` 0 1 3 4 ```
Formula / Mathematical Form
Not applicable for this topic.
Solved Example
Example — Sum of First 10 Positive Numbers
Given: - Range: 1 to 10
Required: - Sum of numbers 1 to 10
Code: ```python sum = 0 for i in range(10): sum = sum + (i + 1) print('The sum of first ten positive numbers is:', sum) ```
Output: ``` The sum of first ten positive numbers is: 55 ```
| Iteration | i | i+1 | sum |
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 2 | 3 | 6 |
| 4 | 3 | 4 | 10 |
| 5 | 4 | 5 | 15 |
| 6 | 5 | 6 | 21 |
| 7 | 6 | 7 | 28 |
| 8 | 7 | 8 | 36 |
| 9 | 8 | 9 | 45 |
| 10 | 9 | 10 | 55 |
Important Points
- - A loop allows a block of code to be executed repeatedly.
- - The `for` loop is the most commonly used loop in Python.
- - The `range()` function generates a sequence of numbers for the loop.
- - `range(stop)` — starts at 0, ends at stop-1
- - `range(start, stop)` — starts at start, ends at stop-1
- - `range(start, stop, step)` — starts at start, ends at stop-1, step size step
- - The terminating value in `range()` is not inclusive.
- - Step size can be positive or negative.
- - Indentation is critical in Python — incorrect indentation causes errors.
- - The `:` after the for loop statement shows that the following lines are inside the loop.
- - `break` exits the loop immediately.
- - `continue` skips the rest of the current iteration.
- - `else` with a loop executes after the loop completes normally.
- - An infinite loop runs forever — avoid by updating the condition variable.
Remember
- - Loop = Repeated execution of code.
- - for loop = Most common loop in Python.
- - range() = Generates sequence of numbers.
- - **range(5)** = 0, 1, 2, 3, 4
- - **range(1, 5)** = 1, 2, 3, 4
- - **range(10, 20, 2)** = 10, 12, 14, 16, 18
- - Terminating value not inclusive.
- - Indentation = Critical in Python.
- - `:` = Start of loop block.
- - break = Exit loop immediately.
- - continue = Skip to next iteration.
- - Infinite loop = Runs forever — avoid!
Common Mistakes
- - Forgetting the colon (`:`): `for i in range(5)` without `:` causes an error.
- - Incorrect indentation: Code inside the loop must be indented.
- - Thinking range(5) gives 1 to 5: It gives 0 to 4.
- - Forgetting that the terminating value is not inclusive: `range(1, 5)` gives 1 to 4, not 5.
- - Infinite loops: Forgetting to update the condition variable in a while loop.
- - Confusing break and continue: `break` exits the loop; `continue` skips the current iteration.
- - Modifying the loop variable inside the loop: This can cause unexpected behavior.
- - Using the wrong step size: Positive step for increasing sequence, negative for decreasing.
Quick Revision
Computer programs are the most useful in daily life where the same task is to be executed in an iterative fashion. Rather than write code for every part of the same iteration, we incorporate iterations in the programming language to write small code for iterations and execute effectively.
The most commonly used is the `for loop`. In a for loop, we need to assign the starting point and the terminating condition, and the loop will execute the instruction(s) for the defined range. For example, you want to display your name five times — place the `print()` function once within the for loop and define the range to be five.
By default, the index `i` of the for loop starts with 0 with step of 1. Alternatively, we can define the starting point and terminating condition along with the step-size for a for loop.
The terminating value in a loop is not inclusive. We can provide any non-zero value for the step-size, according to which the index value will update itself.
Indentation is critical in Python. The `:` after the for loop statement shows that the lines of code that follow are to be executed in the loop and hence need to be indented.
60-Second Revision
- Loop = Repeated execution of code.
- for loop = Most common loop.
- **range(5)** = 0, 1, 2, 3, 4
- **range(1, 5)** = 1, 2, 3, 4
- **range(10, 20, 2)** = 10, 12, 14, 16, 18
- Terminating value not inclusive.
- Indentation critical!
- `:` starts loop block.
- break = exit loop; continue = skip iteration.
- Warning: Always indent code inside the loop. Forgetting indentation causes errors.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.9 Iteration & Loop
Sticky Notes · Quick Revision
Key Point 1
- Loop = Repeated execution of code.
Key Point 2
- for loop = Most common loop.
Key Point 3
- **range(5)** = 0 to 4.
Key Point 4
- **range(1, 5)** = 1 to 4.
Key Point 5
- **range(10, 20, 2)** = 10, 12, 14, 16, 18.
Key Point 6
- Terminating value not inclusive.
Key Point 7
- Indentation critical!
Key Point 8
- `:` starts loop block.
Key Point 9
- break = exit loop.
Key Point 10
- continue = skip to next iteration.
Key Point 11
- Infinite loop = runs forever.
Same supplied content as this Notes page (shared canonical source).