Unit 2: Computational Thinking & Programming
Chapter 4: Looping Structures
1. Introduction to Iteration
Loops (or iterative statements) repeat a block of code multiple times until a terminating condition is met.
1. Deterministic Loop (for loop) 2. Indeterminate Loop (while loop)
Repeats for every item in a sequence Repeats as long as condition is True
[for item in seq] [while condition]
| |
v v
[Execute Suite] [Evaluate Condition]
| / \
v True False
[Next item exists?] / \
/ \ [Execute Suite] [Exit]
Yes No
/ \
[Loop Back] [Exit]
2. The while Loop
Repeats as long as the test expression evaluates to True. It requires three essential parts:
1. Initialization: Setting the initial value of the loop control variable.
2. Condition: Checking whether the loop should continue.
3. Update: Modifying the loop variable (increment/decrement) so the condition eventually becomes False.
# Printing numbers 1 to 5
i = 1 # 1. Initialization
while i <= 5: # 2. Condition
print(i, end=" ")
i += 1 # 3. Update (Increment)
print("\nDone")
# Output: 1 2 3 4 5
3. The for Loop and the range() Function
In Python, the for loop iterates over members of any sequence (strings, lists, tuples, or numeric ranges).
The range() Function
Generates an immutable sequence of numbers on demand:
range([start,] stop[, step])
start: Initial value (optional, defaults to0).stop: Upper limit (required, exclusive — stops atstop - 1).step: Increment/decrement value (optional, defaults to1).
# range(5) -> 0, 1, 2, 3, 4
for i in range(5):
print(i, end=" ") # Output: 0 1 2 3 4
# range(2, 10, 2) -> 2, 4, 6, 8
for i in range(2, 10, 2):
print(i, end=" ") # Output: 2 4 6 8
# Negative step: range(10, 0, -2) -> 10, 8, 6, 4, 2
for i in range(10, 0, -2):
print(i, end=" ") # Output: 10 8 6 4 2
4. Loop Control Statements: break, continue, and pass
| Statement | Purpose | Diagram / Effect |
|---|---|---|
break |
Immediately terminates loop execution and jumps to the statement following the loop. | Loop body -> break -> Exit Loop Immediately |
continue |
Aborts only the current iteration and jumps directly to the next iteration. | Loop body -> continue -> Jump to Next Iteration |
pass |
Null operation; acts as a syntactical placeholder where code is required but no action is needed. | Does nothing |
# Demonstrating break
for num in range(1, 10):
if num == 5:
break
print(num, end=" ")
# Output: 1 2 3 4
# Demonstrating continue
for num in range(1, 6):
if num == 3:
continue
print(num, end=" ")
# Output: 1 2 4 5 (3 skipped)
The else Clause with Loops
Python loops support an optional else block that executes only if the loop finishes normally (without encountering a break statement):
# Prime number checker using loop-else
n = int(input("Enter an integer: "))
if n > 1:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
print(f"{n} is Composite (divisible by {i}).")
break
else:
print(f"{n} is a Prime Number.")
else:
print(f"{n} is neither prime nor composite.")
5. Nested Loops and Classic Algorithms
Fibonacci Series Generation
Generate the first $N$ terms of the Fibonacci sequence: $0, 1, 1, 2, 3, 5, 8, 13, \dots$
n = int(input("Enter number of terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
Star Pattern Generation
Print an inverted right-angled triangle:
rows = 5
for i in range(rows, 0, -1):
for j in range(i):
print("*", end=" ")
print()
Output:
* * * * *
* * * *
* * *
* *
*
6. Board Exam Practice Questions & Solutions
Q1. How many times will the following loop execute? What will be the final printed value of s?
s = 0
for i in range(5, 25, 4):
s += i
print("Final Sum:", s)
Answer:
The values generated by range(5, 25, 4) are: $5, 9, 13, 17, 21$.
The loop executes 5 times.
Sum $= 5 + 9 + 13 + 17 + 21 = \mathbf{65}$.
Q2. Write a Python program using a while loop to reverse the digits of a positive integer (e.g., input: 1234, output: 4321).
Answer:
num = int(input("Enter a positive integer: "))
rev = 0
temp = num
while temp > 0:
digit = temp % 10
rev = rev * 10 + digit
temp //= 10
print("Reversed Number:", rev)
Q3. Differentiate between break and continue statements in Python.
Answer:
- The break statement unconditionally terminates the enclosing loop entirely, transferring program control to the first statement outside the loop body.
- The continue statement skips the remaining code within the current iteration only, immediately transferring control to the beginning of the next iteration of the loop.