Big picture
Programs often make decisions and repeat work. A marks-processing program may classify a result, reject an invalid entry and repeat calculations for every student. Selection chooses among paths; iteration repeats a path while preserving a clear rule for progress.
The key exam skill is tracing state. Write the current values, evaluate the condition and record only what actually executes. Indentation determines which statements belong together, so do not treat it as decoration. A short trace can reveal an off-by-one error that a quick visual inspection misses.
Learning goals
Design conditions with correct boundary comparisons.
Distinguish independent decisions, elif chains and nesting.
Trace for and while loops including empty cases.
Use accumulators, counters and loop-control statements.
Test digit-processing and simple search algorithms.
Core ideas
1. Conditions and the if statement
Selection runs statements only when a condition is satisfied. An if header ends with a colon and its body is indented. The condition is evaluated before the body. An independent statement after the block runs regardless of whether that block was entered.
For a pass threshold, test marks >= 40 rather than marks > 40 if exactly forty is a pass. Boundary values expose the difference. Comparisons produce Boolean values, while and, or and not combine conditions. A valid percentage lies between zero and one hundred inclusive, so both bounds must hold. Using or would accept almost every number. Write the intended range in words before translating it to avoid a condition that is syntactically correct but logically useless.
2. if–else, elif and nested selection
An if–else statement selects exactly one of two branches. An elif chain tests alternatives in order and executes the first matching branch. For grades, test the highest threshold first: a score meeting the highest threshold also meets lower thresholds. Independent if statements are different because several can execute.
Nested selection places a decision inside another block. For example, first confirm that marks are valid, then classify the result. This prevents an impossible score from being treated as an excellent result. Align else with its intended if, and use a trace case for each branch. Conditions should cover the intended domain without accidental gaps. An else branch catches all remaining cases, which is helpful only after the earlier tests have been designed carefully.
3. for loops and range
A for loop traverses items from an iterable. range(start, stop, step) provides an arithmetic sequence of integers, excluding stop. The default start is zero and default step is one. A zero step is invalid. A negative step supports descending traversal when start and stop are consistent with it.
for n in range(2, 12, 3):
print(n, end=" ")
print()
print(list(range(8, 1, -2)))Output:
2 5 8 11
[8, 6, 4, 2]The first loop advances by three while remaining below twelve. The second decreases by two while remaining above one. Predicting the iteration values first is safer than counting them from the printed expression. An empty range is legal and executes the body zero times; it is not automatically a runtime error.
4. while loops and termination
A while loop repeatedly tests a condition before executing its body. It may run zero times if the condition is initially false. Its state must eventually change in a way that can make the condition false, unless an intentional exit such as break is used.
For a countdown, initialise a positive counter, test counter > 0, and decrement within the block. Moving the decrement outside can create an infinite loop. A sentinel is a special value that ends input processing, such as a reserved negative value when all valid measurements are non-negative. Test for the sentinel before adding it to a total. When tracing, record the condition before every iteration, including the final failed test; the final state is often what an output question asks for.
5. Accumulators and counters
An accumulator combines values, while a counter records how many events occurred. Start a sum at zero and a product at one, because these are the corresponding identity values. Initialise once before the loop; resetting inside destroys earlier work.
total = 0
count = 0
for value in [6, 9, 12, 15]:
if value % 3 == 0:
total += value
count += 1
print(total, count, total / count)Output:
42 4 10.5All four values meet the condition. The additions produce 6, 15, 27 and 42; the counter reaches four. The mean is 42 ÷ 4 = 10.5. For an empty qualifying set, count remains zero, so guard the division. A program that works on the sample may still fail when no item qualifies.
6. break, continue and pass
break exits the nearest enclosing loop immediately. continue skips the remaining body of the current iteration and begins the next iteration. pass does nothing; it can occupy a syntactically required suite, but it neither repeats nor exits a loop.
For a search, break can stop after finding a match. For processing records, continue can skip an invalid record while allowing later records to be examined. In a while loop, ensure that continue does not bypass the state update needed for progress. Python loops may have an else block, which runs after normal exhaustion or a false while condition, but not after break. Do not confuse loop else with an if branch: its meaning concerns how the loop finished.
7. Nested loops and common algorithms
A nested loop runs an inner traversal for each outer item. If the outer loop has three iterations and the inner loop has two on every pass, the body executes six times. If the inner bounds depend on the outer value, multiply only after checking whether the count is constant.
Use loops for digit processing, factorials and primality tests. To process a positive integer's digits, remainder by ten obtains the final digit and floor division by ten removes it. Handle zero and negative inputs explicitly if allowed. A prime is an integer greater than one with no divisors other than one and itself. A test must reject values below two before checking divisors. These domain checks are part of the algorithm, not optional decoration.
8. Worked digit trace and testing
The following program adds the digits of a positive integer. Each iteration removes exactly one digit, which explains termination.
number = 462
total = 0
while number > 0:
total += number % 10
number //= 10
print(total, number)Output:
12 0The digits encountered are 2, then 6, then 4, giving 12. The number becomes 46, 4 and finally zero. The condition is then false. Reversing the order of the update and extraction would lose the original units digit. Test a single-digit number, a number containing zero and the smallest permitted value. For any algorithm, include a normal case, a boundary case and a case that takes a different branch. State what should happen before running the test so an incorrect implementation cannot define its own expected answer.
A reliable approach to questions
Read the command word before choosing an answer. A definition needs the distinguishing feature; a comparison needs matching criteria on both sides; an application needs a reason linked to the situation.
Extract the supplied evidence and assumptions. Keep a small working table rather than relying on memory. If information is absent, state the limit instead of inventing a value or claiming certainty.
Work through the relevant rule one step at a time. For a program, record the changing state; for a scenario, connect the requirement to the feature that meets it. Explain why the closest alternative fails.
Check the result against the original question, including boundary cases, units and wording. Present a concise final answer followed by enough reasoning for another student to reproduce your conclusion.
Connections that matter
Boolean logic supplies the conditions used by selection.
Strings and collections provide iterable values for loops.
Functions package repeated algorithms for reuse.
Common mistakes
Including the stop value of range: it is excluded.
Resetting an accumulator inside the loop: initialise before repetition.
Using or for an inclusive valid interval: both bounds require and.
Assuming continue updates a while counter: preserve progress explicitly.
Revision checklist
I can design conditions with correct boundary comparisons.
I can distinguish independent decisions, elif chains and nesting.
I can trace for and while loops including empty cases.
I can use accumulators, counters and loop-control statements.
I can test digit-processing and simple search algorithms.