So far, every program you've written ran straight from top to bottom โ line 1, line 2, line 3, done. โฌ๏ธ But real programs need to make decisions ("Is the student pass or fail?") and repeat work ("Print the report card for ALL 40 students"). This chapter gives your programs a BRAIN ๐ง and STAMINA ๐! We'll answer: How does Python choose between two paths? How do we repeat statements using for and while? What does range() really generate? How do break, continue and the loop else clause change the flow? Let's take control! ๐ฎ๐
Type out and run every program yourself โ don't just read them! Focus especially on range() outputs, for vs while, break vs continue, the loop else clause, and nested loop patterns โ these are the source of MOST output-based and program-writing questions in the exam.
8.1 ๐ Introduction
The flow of control is the order in which the statements of a program are executed. In the Introduction to Problem Solving chapter, you learnt that every algorithm uses three basic control structures. Python supports all three:
graph LR
FOC["๐ฎ FLOW OF CONTROL"]
SEQ["โก๏ธ Sequence\nStatements run one\nafter another"]
SEL["๐ Selection\nif, if-else, if-elif-else"]
ITR["๐ Iteration\nfor loop, while loop"]
FOC --> SEQ
FOC --> SEL
FOC --> ITR
style SEQ fill:#2196F3,color:#fff
style SEL fill:#FF9800,color:#fff
style ITR fill:#4CAF50,color:#fff
Think of it this way: A program is like your school day ๐ซ. Most periods happen in a fixed sequence. If it rains, the PT period is replaced by a library period (selection). And the school bell rings again and again at the end of every period (iteration)!
8.2 ๐งฑ Types of Statements in Python
Statements are the instructions given to the computer. Python has three types:
Empty Statement
A statement that does NOTHING; used where syntax needs a statement but no action is required
passSimple Statement
Any single executable statement written on one line
x = 5print(x)Compound Statement
A group of statements executed as a unit; has a header line ending with a colon and an indented body
ifforwhile8.2.1 The pass Statement ๐ซฅ
marks = 45
if marks >= 33:
pass # nothing to do yet โ will add code later
else:
print("Fail")
pass? ๐ง Python does not allow an empty body after a colon. If you write if x > 5: and leave nothing indented under it, you get an IndentationError. pass acts as a placeholder โ "do nothing, but keep the syntax valid".
8.2.2 Compound Statements and Indentation ๐งฉ
A compound statement has a header (ending with a colon :) and a body (a block of statements indented under it).
if marks >= 33: โ header (ends with a colon)
print("Pass") โโ
print("Well done!") โโ body / block (indented by 4 spaces)
print("Result declared") โ NOT part of the if โ back at the left margin
In Python, indentation defines a block โ there are no curly braces { }. All statements of one block must have the same indentation (4 spaces is the standard). Wrong indentation gives an IndentationError or silently changes the logic!
8.3 ๐ Selection โ The if Statements
Selection statements let a program test a condition and decide which statements to execute. A condition is any expression that gives True or False.
graph TD
IFS["๐ SELECTION STATEMENTS"]
A["1๏ธโฃ if\nOne-way decision"]
B["2๏ธโฃ if-else\nTwo-way decision"]
C["3๏ธโฃ if-elif-else\nMulti-way decision"]
D["4๏ธโฃ Nested if\nif inside another if"]
IFS --> A
IFS --> B
IFS --> C
IFS --> D
style A fill:#2196F3,color:#fff
style B fill:#FF9800,color:#fff
style C fill:#4CAF50,color:#fff
style D fill:#9C27B0,color:#fff
8.3.1 The Simple if Statement 1๏ธโฃ
Executes the block only if the condition is True; otherwise the block is skipped.
Syntax:
if condition:
statement(s)
age = int(input("Enter your age: "))
if age >= 18:
print("You can vote! ๐ณ๏ธ")
print("Thank you")
Input 20 โ You can vote! ๐ณ๏ธ
Thank you
Input 15 โ Thank you
8.3.2 The if-else Statement 2๏ธโฃ
Chooses one of two blocks: the if block when the condition is True, the else block when it is False. Exactly one of them always runs.
Syntax:
if condition:
statement(s) # runs when True
else:
statement(s) # runs when False
graph TD
A{"condition\nTrue?"}
B["if block"]
C["else block"]
D["next statement"]
A -->|"True"| B --> D
A -->|"False"| C --> D
style A fill:#FF9800,color:#fff
style B fill:#4CAF50,color:#fff
style C fill:#F44336,color:#fff
Code Example: leap_year.py
# A year is a leap year if it is divisible by 400,
# OR divisible by 4 but NOT by 100
year = int(input("Enter a year: "))
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Input 2024 โ 2024 is a leap year
Input 1900 โ 1900 is not a leap year
Input 2000 โ 2000 is a leap year
"Write a program to check whether a year is a leap year." โ 3-mark program, a board FAVOURITE! Remember the exact rule: divisible by 400, OR divisible by 4 but not by 100. So 1900 is NOT a leap year, but 2000 IS.
8.3.3 The if-elif-else Statement 3๏ธโฃ
Used when there are more than two possibilities. Python checks the conditions from top to bottom and runs the block of the FIRST condition that is True โ the rest are skipped. The final else (optional) runs if no condition is True.
Syntax:
if condition1:
block1
elif condition2:
block2
elif condition3:
block3
else:
block4
Code Example: grade.py
marks = float(input("Enter percentage: "))
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 33:
grade = "D"
else:
grade = "E (Fail)"
print("Grade:", grade)
Input 82 โ Grade: B
Input 30 โ Grade: E (Fail)
If you write if marks >= 33: FIRST, then a student with 95 marks gets grade D, because 95 >= 33 is True and Python stops at the first True condition. Always check from the highest range to the lowest.
elif is just short for "else if". You can have any number of elif blocks, but only one if at the start and at most one else at the end.
8.3.4 Nested if Statements 4๏ธโฃ
An if statement inside another if (or else) block is called a nested if.
Code Example: positive_even.py
num = int(input("Enter a number: "))
if num > 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
elif num < 0:
print("Negative number")
else:
print("Zero")
Input 8 โ Positive even number
Input -3 โ Negative number
Input 0 โ Zero
"Differentiate between if-else and if-elif-else." โ 2-mark question!
Answer: if-else is used for a two-way decision โ one of two blocks is executed. if-elif-else is used for a multi-way decision โ conditions are tested one by one, and the block of the first true condition is executed; if none is true, the else block runs.
8.4 ๐ข The range() Function
Before learning loops, you must master range(). It generates a sequence of integers, and is most often used with the for loop.
Syntax: range(start, stop, step)
start
The first number of the sequence (optional; default is 0)
Includedstop
The sequence goes up to but NOT including this number (required)
Excludedstep
The difference between consecutive numbers (optional; default is 1; cannot be 0)
Can be negative| Call | Numbers Generated | Explanation |
|---|---|---|
range(5) |
0, 1, 2, 3, 4 | start = 0, stop = 5 |
range(2, 7) |
2, 3, 4, 5, 6 | stop 7 is excluded |
range(1, 10, 2) |
1, 3, 5, 7, 9 | jump by 2 |
range(10, 0, -2) |
10, 8, 6, 4, 2 | counting DOWN |
range(5, 1, -1) |
5, 4, 3, 2 | 1 is excluded |
range(5, 2) |
(nothing) | can't go up from 5 to 2 with step +1 |
print(list(range(1, 10, 3))) # [1, 4, 7]
print(list(range(0, -5, -1))) # [0, -1, -2, -3, -4]
print(len(range(3, 15))) # 12
range(start, stop, step) includes start but excludes stop. The number of values in range(a, b) (step 1) is b โ a. A step of 0 gives a ValueError.
range(1, 10) does NOT include 10! To print 1 to 10, write range(1, 11). Also, range() works only with integers โ range(1.5, 5) gives a TypeError.
8.5 ๐ Iteration โ Loops
Iteration (looping) means repeating a set of statements multiple times. Python has two loops:
graph TD
LOOPS["๐ PYTHON LOOPS"]
FOR["๐ข for loop\nCounting loop\nRepeats for each item\nin a sequence"]
WHILE["โณ while loop\nConditional loop\nRepeats as long as a\ncondition is True"]
LOOPS --> FOR
LOOPS --> WHILE
style FOR fill:#2196F3,color:#fff
style WHILE fill:#FF9800,color:#fff
8.5.1 The for Loop ๐ข
The for loop repeats a block once for each item in a sequence (a range, string, list, tuple, etc.). The loop variable takes the value of each item, one by one.
Syntax:
for variable in sequence:
statement(s)
for i in range(1, 6):
print(i, end=" ")
# Output: 1 2 3 4 5
for ch in "PYTHON":
print(ch, end="-")
# Output: P-Y-T-H-O-N-
How a for loop works:
graph TD
A(["Start"])
B{"Any items left\nin the sequence?"}
C["Assign next item\nto loop variable"]
D["Execute loop body"]
E(["Exit loop"])
A --> B
B -->|"Yes"| C --> D --> B
B -->|"No"| E
style B fill:#FF9800,color:#fff
style D fill:#2196F3,color:#fff
style E fill:#4CAF50,color:#fff
Code Example: multiplication_table.py
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
Input 7 โ 7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Code Example: sum_and_average.py
total = 0
for i in range(1, 6):
marks = float(input("Enter marks of subject " + str(i) + ": "))
total += marks
print("Total =", total)
print("Average =", total / 5)
Code Example: factorial.py
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial of", n, "is", fact)
# Input 6 โ Factorial of 6 is 720
"How many times will the loop run? What is the output?" โ 1 to 2-mark questions every year!
For for i in range(a, b, s), list out the values of i first (remember: stop is excluded), then trace the body for each value.
8.5.2 The while Loop โณ
The while loop repeats a block as long as a condition is True. It is used when we don't know in advance how many times the loop must run.
Syntax:
while condition:
statement(s)
A while loop has four parts:
count = 1 โ Initialisation โ give the loop variable a starting value
while count <= 5: โก Test condition โ checked BEFORE every iteration
print(count) โข Body โ the statements to repeat
count += 1 โฃ Update โ change the loop variable
graph TD
A["โ count = 1"]
B{"โก count <= 5 ?"}
C["โข print(count)"]
D["โฃ count += 1"]
E(["Loop ends"])
A --> B
B -->|"True"| C --> D --> B
B -->|"False"| E
style B fill:#FF9800,color:#fff
style C fill:#2196F3,color:#fff
style D fill:#9C27B0,color:#fff
style E fill:#4CAF50,color:#fff
Code Example: sum_of_digits.py
num = int(input("Enter a number: "))
total = 0
while num > 0:
digit = num % 10 # get the last digit
total += digit
num = num // 10 # remove the last digit
print("Sum of digits =", total)
# Input 4721 โ Sum of digits = 14
Dry run for num = 4721:
| num | digit = num % 10 | total | num // 10 |
|---|---|---|---|
| 4721 | 1 | 1 | 472 |
| 472 | 2 | 3 | 47 |
| 47 | 7 | 10 | 4 |
| 4 | 4 | 14 | 0 |
| 0 | loop ends | โ | โ |
Code Example: palindrome_number.py
num = int(input("Enter a number: "))
original = num
reverse = 0
while num > 0:
reverse = reverse * 10 + num % 10
num = num // 10
if original == reverse:
print(original, "is a palindrome")
else:
print(original, "is not a palindrome")
# Input 1221 โ 1221 is a palindrome
# Input 1234 โ 1234 is not a palindrome
If you forget the update step (e.g., count += 1), the condition never becomes False, and the loop runs forever. In IDLE, press Ctrl + C to stop it.
count = 1
while count <= 5:
print(count) # โ count never changes โ prints 1 forever!for vs while โ The Critical Comparison:
| Feature | for loop |
while loop |
|---|---|---|
| Type | Counting loop | Conditional loop |
| Used when | The number of repetitions is known (or a sequence is given) | The number of repetitions is not known in advance |
| Loop variable update | Automatic (takes the next item) | Must be done manually in the body |
| Risk of infinite loop | Very low | High, if the update is forgotten |
| Example | Print a table from 1 to 10 | Sum the digits of a number |
"Differentiate between for and while loops." โ 2-mark question!
Answer: The for loop is a counting loop that repeats for each item of a sequence; it is used when the number of iterations is known. The while loop is a conditional loop that repeats as long as a condition is True; it is used when the number of iterations is not known in advance.
8.6 ๐ฆ Jump Statements โ break and continue
Jump statements change the normal flow of a loop.
break
Immediately TERMINATES the loop; control jumps to the first statement AFTER the loop
Exit the loopcontinue
SKIPS the rest of the current iteration and jumps to the NEXT iteration
Skip this roundfor i in range(1, 8):
if i == 4:
break
print(i, end=" ")
# Output: 1 2 3
for i in range(1, 8):
if i == 4:
continue
print(i, end=" ")
# Output: 1 2 3 5 6 7
graph LR
subgraph BR["๐ break"]
B1["1"] --> B2["2"] --> B3["3"] --> B4["4 โ STOP"]
end
subgraph CO["โญ๏ธ continue"]
C1["1"] --> C2["2"] --> C3["3"] --> C4["4 โญ๏ธ skip"] --> C5["5"] --> C6["6"] --> C7["7"]
end
style B4 fill:#F44336,color:#fff
style C4 fill:#FF9800,color:#fff
Analogy: You're eating a plate of 7 pani-puris ๐ฅ.
break: at puri 4 you find a chilli ๐ถ๏ธ and STOP eating altogether.continue: you find puri 4 is broken, so you SKIP just that one and carry on with 5, 6 and 7!
Code Example: prime_check.py
num = int(input("Enter a number: "))
is_prime = True
if num < 2:
is_prime = False
for d in range(2, num):
if num % d == 0:
is_prime = False
break # a factor found โ no need to check further
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
# Input 29 โ 29 is a prime number
# Input 91 โ 91 is not a prime number (91 = 7 x 13)
"Differentiate between break and continue." โ 2-mark question, asked EVERY year!
Answer: break terminates the loop completely, and control passes to the statement after the loop. continue skips only the remaining statements of the current iteration, and the loop continues with the next iteration.
8.7 ๐ The Loop else Clause
Both for and while loops can have an optional else block. It runs only when the loop ends normally โ that is, NOT because of a break.
graph TD
L["๐ Loop runs"]
Q{"How did the\nloop end?"}
N["โ
Normally\n(sequence over / condition False)"]
B["๐ By break"]
E["else block RUNS"]
S["else block SKIPPED"]
L --> Q
Q --> N --> E
Q --> B --> S
style E fill:#4CAF50,color:#fff
style S fill:#F44336,color:#fff
Code Example: prime_with_else.py
num = int(input("Enter a number (2 or more): "))
for d in range(2, num):
if num % d == 0:
print(num, "is not prime; it is divisible by", d)
break
else:
print(num, "is prime") # runs only if break never happened
# Input 17 โ 17 is prime
# Input 15 โ 15 is not prime; it is divisible by 3
i = 1
while i <= 3:
print(i, end=" ")
i += 1
else:
print("-> loop over")
# Output: 1 2 3 -> loop over
Students think the loop else runs when the loop condition is False at the start, or "when the if inside is False". โ No! The loop else runs whenever the loop finishes without a break โ even if the loop body ran zero times.
8.8 ๐ช Nested Loops
A loop inside another loop is a nested loop. For every single iteration of the outer loop, the inner loop runs completely.
for i in range(1, 4): # outer loop โ 3 times
for j in range(1, 3): # inner loop โ 2 times for EACH i
print(i, j)
# Total prints = 3 x 2 = 6
1 1
1 2
2 1
2 2
3 1
3 2
Analogy: A clock โฐ! The hour hand is the outer loop and the minute hand is the inner loop. For every ONE move of the hour hand, the minute hand completes a FULL round of 60 minutes.
Pattern programs โ a favourite of board exams:
Code Example: star_triangle.py
n = 4
for i in range(1, n + 1): # row number
for j in range(i): # print i stars in row i
print("*", end=" ")
print() # move to the next line
*
* *
* * *
* * * *
Code Example: number_pattern.py
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end=" ")
print()
1
1 2
1 2 3
1 2 3 4
Code Example: inverted_pattern.py
for i in range(4, 0, -1):
print("*" * i)
****
***
**
*
In pattern programs, the outer loop controls the ROWS and the inner loop controls what is printed in each row (the COLUMNS). Use print(..., end=" ") to stay on the same line and an empty print() to move to the next line.
"How many times will the inner statement execute?" โ Multiply! If the outer loop runs m times and the inner loop runs n times for each, the inner body executes m ร n times (when the inner count does not depend on the outer variable).
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
โ Missing colon: if x > 5 |
Every header needs a colon | โ
if x > 5: โ otherwise SyntaxError |
โ Using = in a condition: if x = 5: |
= is assignment |
โ
Use == for comparison |
โ Writing else if |
Not valid Python | โ
Use elif |
โ range(1, 10) includes 10 |
stop is excluded | โ
Gives 1 to 9; use range(1, 11) for 1 to 10 |
โ Forgetting to update the while variable |
Condition never becomes False | โ Always update, or you get an infinite loop |
โ break and continue do the same thing |
break exits, continue skips | โ
break ends the loop; continue skips to the next iteration |
โ Loop else runs when the loop condition is False at the start only |
Misreading the rule | โ
Loop else runs whenever the loop ends without break |
โ Wrong order in if-elif (>= 33 checked before >= 90) |
First True condition wins | โ Check from highest range to lowest |
| โ Inconsistent indentation inside a block | Python uses indentation for blocks | โ Keep the same indentation (4 spaces) for the whole block |
๐ Quick Revision โ Exam Ready!
Statement Types:
- Empty โ
pass(placeholder, does nothing) - Simple โ single line, e.g.
x = 5 - Compound โ header with
:+ indented body, e.g.if,for,while
Selection:
| Statement | Use |
|---|---|
if |
One-way decision |
if-else |
Two-way decision |
if-elif-else |
Multi-way decision (first True wins) |
Nested if |
if inside another if |
range(start, stop, step):
- start included (default 0) ยท stop excluded ยท step default 1, can be negative, never 0
range(5)โ 0 1 2 3 4 ยทrange(2, 10, 3)โ 2 5 8 ยทrange(5, 0, -1)โ 5 4 3 2 1
Loops:
forโ counting loop; repeats for each item in a sequencewhileโ conditional loop; needs initialisation, condition, body, update
Jump Statements:
breakโ exits the loop immediatelycontinueโ skips to the next iteration
Loop else โ runs only when the loop ends normally (no break)
Nested loops โ inner loop runs fully for each outer iteration; total = outer ร inner
๐ฏ Sample Board Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the output of print(list(range(2, 11, 3)))?
โ [2, 5, 8]
b) Which statement is used as a placeholder that does nothing?
โ pass
c) How many times will for i in range(10, 0, -2): run?
โ 5 times (10, 8, 6, 4, 2)
d) Which keyword is used in Python instead of "else if"?
โ elif
e) Which jump statement skips the rest of the current iteration?
โ continue
Q2: Output Based [2 marks]
Q: Write the output of the following code:
for i in range(1, 10):
if i % 3 == 0:
continue
if i == 8:
break
print(i, end=" ")
else:
print("Done")
print("End")
Answer:
1 2 4 5 7 End
(3 and 6 are skipped by continue; at i = 8 the loop breaks, so the loop's else does NOT run.)
Q3: Find the Errors [2 marks]
Q: Rewrite the code after removing all errors. Underline each correction.
n = int(input("Enter n"))
if n > 0
for i in range(1, n+1):
print(i)
else if n == 0:
print("Zero")
Answer:
n = int(input("Enter n"))
if n > 0: # colon added
for i in range(1, n+1):
print(i) # indentation fixed
elif n == 0: # 'else if' changed to 'elif'
print("Zero")
Q4: Output Based [3 marks]
Q: Write the output of the following code:
x = 10
count = 0
while x > 0:
x = x - 3
count += 1
print(x, count)
for a in range(3):
for b in range(a, 3):
print(a + b, end=" ")
print()
Answer:
-2 4
0 1 2
2 3
4
(x goes 10 โ 7 โ 4 โ 1 โ โ2, so the loop runs 4 times. In the nested loop, the inner range starts at a.)
Q5: Program [3 marks]
Q: Write a program to print the Fibonacci series up to n terms (0 1 1 2 3 5 โฆ).
n = int(input("How many terms? "))
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
# Input 8 โ 0 1 1 2 3 5 8 13
โ๏ธ Practice Problems
-
Write a program to input three numbers and print the largest using
if-elif-else. -
Write a program to input the cost price and selling price of an item and print whether there is a profit, a loss, or neither โ and by how much.
-
Write the output of: (a)
list(range(7))(b)list(range(3, 20, 4))(c)list(range(20, 3, -5))(d)list(range(4, 4)) -
Write a program to print all even numbers from 1 to 50 using a
forloop, and then again using awhileloop. -
Write a program to count the number of digits in an integer using a
whileloop. -
Write a program to check whether a number is an Armstrong number (e.g., 153 = 1ยณ + 5ยณ + 3ยณ).
-
Write a program to print all prime numbers between 1 and 100 (use a nested loop with
break). -
Write a program to print the following pattern for n = 5:
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 -
Explain the loop
elseclause with a program that searches for a number in a range and prints "Not found" using theelseclause. -
Convert the following
whileloop into an equivalentforloop:i = 5 while i <= 25: print(i) i += 5