6. Control Statements
Higher Secondary · Computer Science · Science Stream

Control Statements

Beyond sequential flow — how Python programs make decisions with if, elif, else, and match-case, and how they repeat actions with while and for loops, guided by break, continue, pass, and the loop else clause.

6.2 · Live Tool

Decision Lab

Pick one of the chapter's decision-making problems, enter a value, and watch the conditions get evaluated one by one — exactly the way Python checks them from top to bottom.

Trace a Decision

● live
Choose a scenario, enter a value, and press Run.
Each line shows a condition Python checks and whether it's True or False — as soon as one is True, the rest are skipped.
6.1

Control Statements in Python

Sequential programs execute instructions one after another in a fixed order. But real life involves choices — a route based on traffic, a course after Class 10, eligibility for an exam. Control statements let a program make decisions, repeat actions, or skip instructions.

How Decisions Get Made

The Arithmetic and Logic Unit (ALU) evaluates comparisons — greater than, less than, equal to — and returns True or False. This logical result guides the program to execute, skip, or choose between statements.

Two Broad Categories

Decision making (selection) statements choose between alternative paths. Iteration (looping) statements repeat a set of instructions until a condition is satisfied.

Algorithm — height of the taller student Step 1: Start Step 2: Input H1, H2 Step 3: If H1 > H2 Then Step 4: Print H1 Step 5: Else Step 6: Print H2 Step 7: End of If Step 8: Stop A rhombus is the flowchart decision symbol — one entry point, two exit points: one path when the condition is True, another when it's False.

Python provides five types of decision-making statements: if, if...else, if...elif...else, match...case, and nested if...else.

6.2.1 – 6.2.3

if, if...else, and if...elif...else

These three constructs let a program choose one action, choose between two, or choose one among several — based on conditions checked from top to bottom.

6.2.1 if Statement

Executes a block only when the condition is True; otherwise the block is skipped entirely. A colon follows the condition, and the block must be indented — indentation is mandatory in Python and defines the scope of the block. Missing it raises an IndentationError.

if condition: block of code
Problem 6.1 — pass score congratulatory message score = int(input("Enter the score: ")) if score >= 30: print("Congratulations... You scored above pass mark.") print("Your score is", score) Enter the score: 28 Enter the score: 35 Your score is 28 Congratulations... You scored above pass mark. Your score is 35

6.2.2 if...else Statement

Used when a program must choose between exactly two alternative actions. If the condition is True, Statement block 1 runs; otherwise Statement block 2 runs. Only one block ever executes.

if condition: Statement block 1 else: Statement block 2
Problem 6.4 — taller of two students h1 = int(input("Enter the height of first student: ")) h2 = int(input("Enter the height of second student: ")) if h1 > h2: print("Larger height is: ", h1) else: print("Larger height is: ", h2)

6.2.3 if...elif...else Ladder

Used when there are more than two alternatives. Conditions are checked top to bottom; as soon as one is True, its block runs and the rest are skipped. The final else is optional and catches the case where none matched.

if condition1: Statement Block 1 elif condition2: Statement Block 2 ... else: Statement Block to execute when all conditions above are False
Problem 6.5 — Positive, Negative or Zero n = int(input("Enter a number: ")) if n > 0: print(n, "is positive") elif n < 0: print(n, "is negative") else: print(n, "is zero")

The number of elif blocks depends on how many conditions need testing — Problem 6.7's grading program (Table 6.1) chains eight such conditions to assign A+ through E based on score range.

6.2.4

match – case Statement

Introduced in Python 3.10, match-case compares a value against several fixed patterns and runs the block for the first match — a cleaner alternative to long if...elif chains when the decision depends on a single variable's value.

match expression: case value1: Statements Block 1 case value2: Statements Block 2 ... case _: Default Statements Block

The special underscore _ case acts as the default, catching anything that matched no earlier case — useful for menu options, weekday names, fixed codes, or grades.

Problem 6.6 — day of the week day = int(input("Enter a number (1-7): ")) match day: case 1: print("Sunday") case 2: print("Monday") ... case 7: print("Saturday") case _: print("Invalid day number")

Pattern Guards (if)

A case can include its own condition — case s if 90 <= s <= 100: — letting match-case group score ranges into grades (Problem 6.7) instead of testing single fixed values.

The | (Pipe) Pattern

case 10 | 9: matches either 10 or 9 with one block — part of pattern-matching syntax, not the logical or. Writing case 10 or 9: is invalid, since or returns a Boolean, not a pattern.

score = 10 match score: case 10 | 9: print("Excellent") Excellent
6.2.5

Nesting & the Nested if...else Statement

Writing one decision-making statement inside any part of another is called nesting. It's needed when a second-level decision only makes sense after the first condition is evaluated.

Nested Inside if

if condition1: if condition2: both True else: cond1 True, cond2 False else: condition1 False

Nested Inside else

if condition1: condition1 True else: if condition2: cond1 False, cond2 True else: both False

Problem 6.8 — Leap year check year = int(input("Enter a year: ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year") else: print("Not a leap year") else: print("Leap year") else: print("Not a leap year")
Input YearDivisible by 4?Divisible by 100?Divisible by 400?Output
2000YesYesYesLeap year
2001No——Not a leap year
2004YesNo—Leap year
2100YesYesNoNot a leap year

Try the leap year check with your own year in the Decision Lab above — its trace follows exactly this nested path.

6.3 – 6.4

Iteration: while and for Loops

Iteration means executing a set of statements repeatedly as long as a condition holds — automating repetitive tasks instead of rewriting instructions, like adding six subject marks one at a time.

6.3.1 Parts of a Loop

Every loop — whatever form it takes in code — is built from the same four components.

Walk Through the Four Parts

● live
—

—

Based on Problem 6.10 — finding the sum and average of scores in 6 subjects.

6.4.1 while Loop — the Indefinite Loop

Used when the number of repetitions isn't known in advance and depends entirely on a condition. It runs as long as the condition stays True and stops the moment it becomes False. Python doesn't build initialisation or updation into the syntax — the programmer writes both separately.

while condition: statements
Problem 6.11 — count the digits in a number n = int(input("Enter a number: ")) count = 0 while n > 0: count = count + 1 n = n // 10 print("Number of digits:", count) Enter a number: 321 → Number of digits: 3

6.4.2 for Loop — the Definite Loop

Used when the number of repetitions is known beforehand — iterating through a range of values or the elements of a string, list, or tuple.

range(n)

Generates numbers from 0 up to n-1. range(5) → 0, 1, 2, 3, 4.

range(start, stop)

Generates numbers from start up to, but not including, stop. range(1,11) → 1 … 10.

range(start, stop, step)

Adds a step size — e.g. 2 for even numbers, or negative for counting down. A positive step with start > stop gives an empty sequence.

range() Explorer

● live
Sequence will appear here.
Mirrors for variable in range(start, stop, step): — capped at 200 values for display.
for loop with a string (Problem 6.15) text = input("Enter a string: ") for ch in text: print(ch, end=" ") Enter a string: Python is interesting P y t h o n i s i n t e r e s t i n g

for loops can also step through lists, tuples, and other collections item by item — covered in detail in later chapters. In Python, the underscore _ can replace the loop variable when its value is never used: for _ in range(5): print("Hello") simply repeats an action.

for vs while — Comparison

Aspectfor Loopwhile Loop
NatureDefinite — repetitions known in advanceIndefinite — depends on a condition
ControlIterates over a sequence (range, list, tuple, string)Repeats while the condition remains true
Init & UpdateUsually handled automatically (e.g. by range())Must be written manually, before and inside the loop
Condition CheckingImplicitly controlled by the sequence/rangeExplicitly tested before every iteration
Typical UseFixed counts, sequences, tablesInput-driven or condition-driven loops
Watch out — the Infinite Loop An infinite loop happens when the condition never becomes False — usually because the updation step is missing or wrong. The loop keeps running without stopping, potentially freezing or slowing the system. Always confirm the update step moves the loop toward its stopping condition.
6.5

Loop Control Statements

Four keywords let a program interrupt, skip, or extend a loop's normal flow instead of running unconditionally until the condition turns False.

break

Exits the loop immediately, even if its condition is still True. Control jumps to the first statement after the loop.

continue

Skips the rest of the current iteration's statements and jumps straight to the next iteration — the loop itself keeps running.

pass

A null statement — does nothing. Used as a placeholder where a statement is syntactically required but no action is needed yet.

else (with loops)

Runs only if the loop finishes all its iterations normally — skipped entirely if a break ended the loop early.

Problem 6.16 — break in a for loop for roll in range(1, 11): print("Roll Number:", roll) if roll == 5: print("Stopping attendance check.") break → prints Roll Number 1 through 5, then stops — 6 to 10 never run.
Problem 6.18 — continue in a for loop for roll in range(1, 11): if roll == 5: continue print("Roll Number:", roll) → prints every roll number from 1 to 10 EXCEPT 5 — the loop doesn't stop.
Problem 6.20 — else with a for loop (prime check) n = int(input("Enter a number: ")) for i in range(2, n): if n % i == 0: print("Not a prime number") break else: print("Prime number") → else runs ONLY if the loop never hit break, i.e. no divisor was found. Enter a number: 49 → Not a prime number Enter a number: 59 → Prime number
KeywordPurposeEffect on Loop Execution
breakTerminates the loop immediatelyExits the loop entirely
continueSkips the current iterationProceeds to the next iteration
passDoes nothing (placeholder)Loop continues normally
elseExecutes after the loop completes normallySkipped if the loop ends with break
6.6

Nested Loops

A loop written inside another loop — the outer loop and the inner loop — models two-level repetitive tasks: entering marks for every subject of every student, or filling every cell of a table.

6.6.1 Nested for

for var1 in sequence1: # Outer for var2 in sequence2: # Inner statements

Each single run of the outer loop lets the inner loop complete all of its iterations before the outer loop advances.

6.6.2 Nested while

while condition1: # Outer while condition2: # Inner statements

Useful for two-level condition-controlled tasks — printing patterns, or processing rows and columns whose extent isn't fixed in advance.

Problem 6.22 — 5 × 5 multiplication table (nested for) for i in range(1, 6): for j in range(1, 6): print(i, '*', j, '=', i*j) print() → outer loop picks i = 1..5; for each i, the inner loop runs j = 1..5.
Problem 6.23 — right-angled triangle (nested while) i = 1 while i <= 5: j = 1 while j <= i: print(j, end=" ") j = j + 1 print() i = i + 1 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

break and continue inside a nested loop act only on the loop they're written in — a break in the inner loop stops only that inner loop and hands control back to the outer loop, it does not exit both at once.

Let Us Do

Quick Recap

Tap a question to reveal the answer.

Spot the error: if n > 0 followed by an indented print("Positive") on the next line.

Syntax error — the condition line is missing its colon. It should read if n > 0:.

Spot the error: an if block and its else block are both written starting at column 0, with no indentation under either.

Indentation error — Python needs the statements belonging to the if and else blocks to be indented consistently under their respective headers; without it, Python cannot tell what belongs to each block.

Spot the logical error: a leap-year checker using if year % 4 == 0: ... elif year % 100 == 0: ... elif year % 400 == 0: ...

The elif conditions are ordered wrongly and the logic contradicts itself — a year divisible by 100 is being labelled "Not a leap year" even though divisibility by 400 (checked separately, and never reached because the 100-check already matched) should override that. It needs to be a nested check: divisible by 100 should only disqualify a year if it is NOT also divisible by 400.

Spot the error: if mark = 30: print("Pass")

Syntax error — = is the assignment operator; comparison needs ==. It should read if mark == 30: (though for a "pass" condition, mark >= 30 would match the chapter's actual eligibility rule).

What does match score // 10: with cases 10 | 9, 8, 7, and _ print when score = 85?

85 // 10 is 8, which matches case 8:, so it prints A.

Why does a for i in range(10, 1): loop never execute?

Because the step defaults to +1, and range() with a positive step where start > stop produces an empty sequence. It would need a negative step, e.g. range(10, 1, -1), to count down.

Spot the logical error: a factorial program initialises fact = 0 before a while n > 0: loop that does n = n - 1 but never multiplies into fact.

Two problems: fact should start at 1 (not 0, since anything multiplied by 0 stays 0), and the loop body is missing the line fact = fact * n before decrementing n — otherwise fact never accumulates the product.

In a nested for loop that reads marks for 5 students across 6 subjects, why is total reset to 0 inside the outer loop rather than before it?

Because each student's total must start fresh. If total = 0 were placed only once before the outer loop, the second student's marks would keep accumulating on top of the first student's total instead of starting a new sum.

What's the key difference between how break and continue affect a loop?

break exits the loop entirely, skipping any remaining iterations. continue only skips the rest of the current iteration and lets the loop carry on to the next one.