So far, every program you wrote ran line by line, from top to bottom โ every line, every time. But real life isn't like that! ๐ฆ You decide things ("If it rains, take an umbrella") and you repeat things ("Do 20 push-ups"). This chapter answers the BIG questions: How can a program make decisions? How can it repeat a task many times without writing the same line again and again? What do if, elif, else, for, while, range(), break and continue do? Let's take control! ๐ฎ
The most tested topics are ifโelifโelse programs, range() outputs, for vs while, break vs continue, and output questions on loops. For every loop, make a small dry-run table (value of the variable in each round) โ that's how toppers solve output questions without mistakes!
5.1 ๐ Introduction โ Three Kinds of Flow
The order in which statements run is called the flow of control. Every program uses a mix of three kinds:
graph LR
subgraph SEQ["โก๏ธ Sequence"]
direction TB
S1["Step 1"] --> S2["Step 2"] --> S3["Step 3"]
end
subgraph SEL["๐ Selection"]
direction TB
C{"Condition?"} -->|"True"| Y["Do this"]
C -->|"False"| N["Do that"]
end
subgraph ITR["๐ Iteration"]
direction TB
L{"Repeat\nagain?"} -->|"Yes"| B["Do the task"]
B --> L
end
SEQ ~~~ SEL ~~~ ITR
Sequence
Statements run one after another from top to bottom
Default flowSelection (Decision)
A condition decides WHICH statements run
ifelifelseIteration (Looping)
A group of statements runs AGAIN AND AGAIN
forwhileAnalogy: Getting ready for school ๐:
- Sequence: wake up โ brush โ bathe โ eat breakfast.
- Selection: if it's Monday, wear the white uniform; else wear the coloured one.
- Iteration: repeat "chew" until the food is finished! ๐
5.1.1 Indentation โ Python's Way of Making Blocks ๐ฆ
A block (or suite) is a group of statements that belong together. Python shows a block using indentation (spaces at the start of the line) after a line ending with a colon :.
if marks >= 33: โ header line ends with a colon
print("Pass") โ
print("Well done!") โ block โ indented by 4 spaces
print("Result declared") โ back to the left โ outside the block
Mixing 4 spaces and 3 spaces, or forgetting to indent after the colon, gives an IndentationError. Forgetting the colon gives a SyntaxError.
5.1.2 The Empty Statement โ pass ๐ค
Sometimes Python needs a statement in a block, but you have nothing to write yet. Use pass โ it does nothing.
marks = 45
if marks > 90:
pass # will add a prize message later
print("Checked")
Output:
Checked
5.2 ๐ Selection โ The if Statements
5.2.1 Simple if โ๏ธ
Runs the block only if the condition is True. If it is False, the block is skipped.
if condition:
statements
temperature = 38
if temperature > 35:
print("It's very hot! Drink water. ๐ง")
print("Have a nice day")
Output:
It's very hot! Drink water. ๐ง
Have a nice day
5.2.2 ifโelse โ๏ธ
Chooses between two paths: one for True, the other for False.
graph TD
C{"๐ค Condition\nTrue?"}
T["โ
if-block runs"]
F["โ else-block runs"]
E["โก๏ธ Next statement"]
C -->|"True"| T --> E
C -->|"False"| F --> E
style T fill:#4CAF50,color:#fff
style F fill:#F44336,color:#fff
num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, "is EVEN")
else:
print(num, "is ODD")
Sample run (the user types 7):
Enter a number: 7
7 is ODD
Analogy: An
ifโelseis like a railway track switch ๐ โ the train goes on ONE track or the OTHER, never both!
5.2.3 ifโelifโelse Ladder ๐ช
When there are more than two choices, use elif (short for "else if"). Python checks the conditions from top to bottom and runs only the first block whose condition is True.
Code Example: grade.py
marks = int(input("Enter marks: "))
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
elif marks >= 33:
print("Grade D")
else:
print("Fail - try again!")
Sample run (the user types 82):
Enter marks: 82
Grade B
How Python checks it for 82:
82 >= 90 ? False โ skip
82 >= 75 ? True โ print "Grade B" โ STOP checking the rest
If you write if marks >= 33 FIRST, then even 95 marks will print "Grade D", because that condition is True and Python stops there. Always put the strictest condition first.
ifcomes first and only once.- You can have any number of
elifs. elseis optional, comes last, and has no condition.- Only ONE block runs, even if many conditions are True.
5.2.4 Nested if ๐ช
An if inside another if is called a nested if. It is used when one decision depends on another.
age = 20
has_licence = False
if age >= 18:
if has_licence:
print("You can drive ๐")
else:
print("Get a licence first ๐")
else:
print("Too young to drive")
Output:
Get a licence first ๐
Largest of three numbers โ a very common exam program:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a >= b and a >= c:
print("Largest is", a)
elif b >= c:
print("Largest is", b)
else:
print("Largest is", c)
Sample run (the user types 12, 45 and 30):
Enter a: 12
Enter b: 45
Enter c: 30
Largest is 45
"Write a program to input a year and check whether it is a leap year." โ 3 marks Answer: A year is a leap year if it is divisible by 400, OR divisible by 4 but not by 100.
year = int(input("Enter year: "))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("Leap year")
else:
print("Not a leap year")
(2024 โ Leap year, 1900 โ Not a leap year, 2000 โ Leap year)
5.3 ๐ข The range() Function
Before learning loops, let's meet their best friend โ range(). It produces a sequence of numbers.
| Form | Produces | Example | Numbers |
|---|---|---|---|
range(stop) |
0 up to stop โ 1 | range(5) |
0 1 2 3 4 |
range(start, stop) |
start up to stop โ 1 | range(2, 7) |
2 3 4 5 6 |
range(start, stop, step) |
start, jumping by step, before stop | range(1, 10, 2) |
1 3 5 7 9 |
| Negative step | Counts down | range(10, 0, -3) |
10 7 4 1 |
print(list(range(5)))
print(list(range(2, 7)))
print(list(range(1, 10, 2)))
print(list(range(10, 0, -3)))
print(list(range(5, 1)))
Output:
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6]
[1, 3, 5, 7, 9]
[10, 7, 4, 1]
[]
range(1, 5) gives 1 2 3 4 โ not 5. To count 1 to 10, write range(1, 11).
Think of stop as a wall ๐งฑ โ you walk right up to it but never step on it!
5.4 ๐ The for Loop
A for loop repeats a block once for each item in a sequence (a range, a string, a listโฆ). Use it when you know how many times to repeat.
for variable in sequence:
statements
for i in range(1, 6):
print("Round", i)
print("Loop over!")
Output:
Round 1
Round 2
Round 3
Round 4
Round 5
Loop over!
Analogy: A
forloop is like a teacher taking attendance ๐งโ๐ซ โ she goes through the register one name at a time, from the first to the last, and does the same thing for each ("Present?").
A for loop over a string:
for ch in "PYTHON":
print(ch, end=" ")
Output:
P Y T H O N
Code Example: table.py โ Multiplication Table
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
Sample run (the user types 7):
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
Code Example: sum_n.py โ Sum of 1 to N
n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i
print("Sum =", total)
Sample run (the user types 5):
Enter N: 5
Sum = 15
Dry run โ how total changes (N = 5):
| i | total = total + i |
|---|---|
| 1 | 0 + 1 = 1 |
| 2 | 1 + 2 = 3 |
| 3 | 3 + 3 = 6 |
| 4 | 6 + 4 = 10 |
| 5 | 10 + 5 = 15 |
To add things up, start with total = 0 before the loop and do total += โฆ inside it. To multiply (e.g. factorial), start with product = 1!
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, "=", fact)
Sample run (the user types 5):
Enter a number: 5
Factorial of 5 = 120
5.5 ๐ The while Loop
A while loop repeats a block as long as a condition is True. Use it when you don't know in advance how many times to repeat.
while condition:
statements
graph TD
I["1๏ธโฃ Initialise\ni = 1"]
C{"2๏ธโฃ Condition\ni <= 5 ?"}
B["3๏ธโฃ Body\nprint(i)"]
U["4๏ธโฃ Update\ni += 1"]
X["๐ Exit loop"]
I --> C
C -->|"True"| B --> U --> C
C -->|"False"| X
style C fill:#FF9800,color:#fff
style U fill:#2196F3,color:#fff
style X fill:#4CAF50,color:#fff
i = 1
while i <= 5:
print(i, end=" ")
i += 1
print()
print("After the loop, i =", i)
Output:
1 2 3 4 5
After the loop, i = 6
- Initialise the variable before the loop (
i = 1) - Test it in the condition (
while i <= 5:) - Update it inside the loop (
i += 1)
If you forget i += 1, i stays 1 forever, the condition is always True, and the loop never stops. (Press Ctrl + C to stop a running program.)
Analogy: A
whileloop is like filling a bucket ๐ชฃ โ "while the bucket is not full, keep pouring water". You don't count the mugs; you just check the condition each time!
Code Example: digits.py โ Sum of Digits
num = int(input("Enter a number: "))
total = 0
while num > 0:
digit = num % 10 # take the last digit
total += digit
num = num // 10 # remove the last digit
print("Sum of digits =", total)
Sample run (the user types 4528):
Enter a number: 4528
Sum of digits = 19
Dry run for 4528:
| num | digit = num % 10 | total | num // 10 |
|---|---|---|---|
| 4528 | 8 | 8 | 452 |
| 452 | 2 | 10 | 45 |
| 45 | 5 | 15 | 4 |
| 4 | 4 | 19 | 0 โ loop stops |
5.5.1 for vs while โ๏ธ
| for loop | while loop |
|---|---|
| Repeats for each item in a sequence | Repeats while a condition is True |
| Used when the number of repetitions is known | Used when it is not known in advance |
| Loop variable updates automatically | You must update the variable yourself |
| e.g. print a table 1 to 10 | e.g. keep asking until the user types a correct password |
"Differentiate between a for loop and a while loop." โ 2 marks
Answer: A for loop repeats once for each item of a sequence (such as range()) and is used when the number of repetitions is known; its loop variable changes automatically. A while loop repeats as long as its condition is True and is used when the number of repetitions is not known in advance; the loop variable must be updated inside the loop.
5.6 ๐ Jump Statements โ break and continue
break
EXITS the loop immediately โ the rest of the rounds are skipped
Stop the loopcontinue
SKIPS only the current round and jumps to the next one
Skip one roundfor i in range(1, 8):
if i == 5:
break
print(i, end=" ")
print("| break done")
for i in range(1, 8):
if i == 5:
continue
print(i, end=" ")
print("| continue done")
Output:
1 2 3 4 | break done
1 2 3 4 6 7 | continue done
Analogy: You're eating a plate of 7 momos ๐ฅ:
- break โ at the 5th momo you're full โ you stop eating completely.
- continue โ the 5th momo fell on the floor โ you skip just that one and eat the rest!
Code Example: prime.py โ Prime Number Check
n = int(input("Enter a number: "))
is_prime = True
if n < 2:
is_prime = False
for i in range(2, n):
if n % i == 0:
is_prime = False
break # a factor is found โ no need to check further
if is_prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number")
Sample run (the user types 13):
Enter a number: 13
13 is a prime number
"Differentiate between break and continue with an example." โ 2 marks
Answer: break ends the loop immediately and control goes to the statement after the loop. continue skips the remaining statements of the current iteration and moves to the next iteration. For example, in for i in range(1, 6), using if i == 3: break prints 1 2, while if i == 3: continue prints 1 2 4 5.
5.7 ๐ช Nested Loops
A loop inside another loop is a nested loop. For each round of the outer loop, the inner loop runs completely.
Analogy: A clock ๐ โ for every 1 hour (outer loop), the minute hand goes round 60 times (inner loop)!
for i in range(1, 4):
for j in range(1, 3):
print("i =", i, "j =", j)
Output:
i = 1 j = 1
i = 1 j = 2
i = 2 j = 1
i = 2 j = 2
i = 3 j = 1
i = 3 j = 2
The outer loop runs 3 times and the inner loop runs 2 times for each โ 3 ร 2 = 6 lines.
Code Example: pattern.py โ Star Pattern
for row in range(1, 5):
for col in range(row):
print("*", end=" ")
print()
Output:
*
* *
* * *
* * * *
Code Example: number_pattern.py
for row in range(1, 5):
for col in range(1, row + 1):
print(col, end=" ")
print()
Output:
1
1 2
1 2 3
1 2 3 4
print() after the inner loop!It moves the output to the next line. Without it, all the stars come on one single line.
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
if marks >= 33 (no colon) |
Header lines need a colon | if marks >= 33: |
if x = 5: |
= stores a value |
Use == to compare |
else marks < 33: |
else takes no condition |
Use elif marks < 33: or just else: |
| Weakest condition first in an elif ladder | Python stops at the first True | Put the strictest condition first |
range(1, 10) includes 10 |
Stop is excluded | It gives 1 to 9; use range(1, 11) for 1 to 10 |
range(10, 1) counts down |
Default step is +1 | Use range(10, 1, -1) |
| while loop without updating the variable | Condition never becomes False | Update it inside the loop (i += 1) |
break skips one round |
break ends the whole loop | continue skips one round |
total = 0 written inside the loop |
It resets every round | Initialise before the loop |
fact = 0 for factorial |
Anything ร 0 = 0 | Start with fact = 1 |
๐ Quick Revision โ Exam Ready!
- Flow of control โ Sequence, Selection (if), Iteration (loops)
- Block โ statements indented equally after a line ending with
: - pass โ empty statement; does nothing
- if โ one choice; ifโelse โ two choices; ifโelifโelse โ many choices, only the first True block runs
- Nested if โ an if inside another if
- range(stop) โ 0 to stopโ1; range(start, stop); range(start, stop, step); stop is never included
- for โ repeats for each item; number of rounds known
- while โ repeats while a condition is True; initialise, test, update
- Infinite loop โ condition never becomes False
- break โ exits the loop; continue โ skips to the next round
- Nested loop โ inner loop runs completely for each round of the outer loop (total = outer ร inner)
- Accumulator โ
total = 0/fact = 1before the loop, update inside
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) Which statement does nothing and is used as a placeholder?
Answer: pass
b) What numbers does range(3, 12, 3) produce?
Answer: 3 6 9
c) Which statement ends a loop immediately?
Answer: break
d) How many times will for i in range(5, 10): run?
Answer: 5 times (5, 6, 7, 8, 9)
e) What is a loop that never ends called? Answer: An infinite loop
Q2: Output Based [2 marks]
x = 15
if x > 10:
print("A")
elif x > 5:
print("B")
else:
print("C")
print("D")
Answer:
A
D
Only the first True block runs, so B is not printed even though x > 5 is also True.
Q3: Output Based [2 marks]
total = 0
for i in range(2, 11, 2):
total += i
print(total)
Answer:
30
i takes 2, 4, 6, 8, 10 โ 2 + 4 + 6 + 8 + 10 = 30.
Q4: Output Based [2 marks]
n = 1
while n < 20:
print(n, end=" ")
n = n * 3
print("End")
Answer:
1 3 9 End
n becomes 1 โ 3 โ 9 โ 27; 27 < 20 is False, so the loop stops.
Q5: Rewrite [2 marks]
Rewrite the following for loop using a while loop:
for i in range(10, 0, -2):
print(i)
Answer:
i = 10
while i > 0:
print(i)
i -= 2
Both print 10, 8, 6, 4, 2 on separate lines.
Q6: Error Finding [2 marks]
Find and correct the errors:
n = int(input("Enter n: "))
if n % 2 = 0
print("Even")
else if:
print("Odd")
Answer:
n = int(input("Enter n: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")
Errors: = should be ==, the colon after the condition was missing, and else if: should be else:.
Q7: Program [3 marks]
Write a program to print all the even numbers from 1 to 20 and their sum.
Answer:
total = 0
for i in range(2, 21, 2):
print(i, end=" ")
total += i
print()
print("Sum =", total)
Output:
2 4 6 8 10 12 14 16 18 20
Sum = 110
โ๏ธ Practice Problems
- Write a program to input a number and print whether it is positive, negative or zero.
- Write a program to input the cost price and selling price of an item and print "Profit", "Loss" or "No profit no loss" with the amount.
- Write the numbers produced by: (a)
range(4)(b)range(3, 9)(c)range(20, 5, -5)(d)range(1, 2, 3) - Write a program to print the squares of numbers from 1 to 10.
- Write a program to input N and print the sum of all odd numbers from 1 to N.
- Write a program to input a number and print its reverse (e.g. 1234 โ 4321) using a while loop.
- Write the output:
for i in range(1, 10): if i % 3 == 0: continuethenprint(i, end=" ")inside the loop. - Write a program that keeps asking for a password until the user types
python123, then prints "Access granted". - Write a program to print this pattern:
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 - Write a program to input a number and print whether it is an Armstrong number (e.g. 153 = 1ยณ + 5ยณ + 3ยณ).
- How many times will
print("Hi")run infor i in range(3): for j in range(4): print("Hi")? - Write a program to input the marks of 5 students using a loop and print the highest marks.