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
● liveControl 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.
Python provides five types of decision-making statements: if, if...else, if...elif...else, match...case, and nested if...else.
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.
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.
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.
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.
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.
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.
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.
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
| Input Year | Divisible by 4? | Divisible by 100? | Divisible by 400? | Output |
|---|---|---|---|---|
| 2000 | Yes | Yes | Yes | Leap year |
| 2001 | No | — | — | Not a leap year |
| 2004 | Yes | No | — | Leap year |
| 2100 | Yes | Yes | No | Not a leap year |
Try the leap year check with your own year in the Decision Lab above — its trace follows exactly this nested path.
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—
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.
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
● livefor 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
| Aspect | for Loop | while Loop |
|---|---|---|
| Nature | Definite — repetitions known in advance | Indefinite — depends on a condition |
| Control | Iterates over a sequence (range, list, tuple, string) | Repeats while the condition remains true |
| Init & Update | Usually handled automatically (e.g. by range()) | Must be written manually, before and inside the loop |
| Condition Checking | Implicitly controlled by the sequence/range | Explicitly tested before every iteration |
| Typical Use | Fixed counts, sequences, tables | Input-driven or condition-driven loops |
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.
| Keyword | Purpose | Effect on Loop Execution |
|---|---|---|
| break | Terminates the loop immediately | Exits the loop entirely |
| continue | Skips the current iteration | Proceeds to the next iteration |
| pass | Does nothing (placeholder) | Loop continues normally |
| else | Executes after the loop completes normally | Skipped if the loop ends with break |
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.
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.
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.