VIEW THIS AS

Auto mode follows the Route Engine until you choose a viewpoint.

YOU ARE HERE

ROUTE CHECK

CONNECTED TO

WHAT NEXT

Use the canonical route for this room, or HELP if you are unsure.

Ministry of Education V3.0 Reference 370 | G3 Computing Python Selection and Loops: Follow the Branch, Prove Termination

A student looks up from her study materials with a hand near her chin, seated at a desk beside a window at sunset.

Why can two Python programmes contain the same comparisons and still produce different answers? The order of `if` and `elif` branches matters, and a loop’s condition is checked at particular moments. One misplaced comparison or missing counter update can change every subsequent step. Control flow is therefore a form of reasoning about a programme’s path rather than a collection of keywords to memorise.

Ministry of Education V3.0 Reference 370 teaches the 2027 Singapore–Cambridge SEC G3 Computing K349 outcomes on Boolean expressions, selection, iteration and interpreting flowcharts. It explains if, elif, else, for and while, and, or, not, range boundaries, nested decisions, loop invariants and termination, with original traces and practical checking methods. The aim is to help students predict which statements execute, how variables change and whether a loop can end.

This independent eduKateSG article is not an official MOE, SEAB or Cambridge publication. The official K349 syllabus and Python quick-reference guide determine the assessment scope. Every example uses fictional quantities and labels; do not use real personal data for simple control-flow practice. Students should predict the result by hand before running any loop, especially where a missing update could create a non-terminating programme.

1. The syllabus boundary

The 2027 K349 Module 2.2.1 expects students to interpret flowcharts showing sequence, selection and iteration. Python outcomes 2.3.6, 2.3.11 and 2.3.12 name Boolean operators or, and, not; selection using if, elif and else; and iteration using for and while. The quick-reference guide shows the common structures.

Related testing outcomes ask candidates to trace variables, locate logic errors and test code incrementally. This guide centres on control flow, not on all features of Python. A correct answer should name the condition, the chosen branch and the loop state rather than merely reporting a final number.

2. Sequence is the default path

Without a branch or loop, Python normally executes statements from top to bottom. If x=2, then x=x+3 and then print(x), the displayed value is 5. An assignment changes the variable for later statements; it does not retrospectively alter earlier output.

Students should trace one line at a time. Even a simple sequence can be misunderstood when a variable is reused with a new value. A short state table recording the current x after every assignment is the foundation for more complicated conditions and loops.

3. A Boolean condition determines a branch

A comparison such as x>5 evaluates to True or False. In an if statement, the indented block is executed only when the condition is true. If x is 7, an if x>5 block runs, while an if x<5 block does not.

Use `==` for an equality comparison, not a single `=`. Assignment and comparison have different purposes. A question that changes one operator may change the selected branch even when the surrounding numbers stay the same.

4. if and else create alternatives

An if/else structure selects between two paths. If the condition is true, the if block executes; otherwise the else block executes. The two blocks are alternatives in a single decision, so the code does not normally execute both.

For instance, a fictional score of 60 with threshold 50 follows the higher branch when the condition is score>=50. A value exactly equal to the threshold reveals whether the comparison is inclusive. Check boundary cases rather than assuming all comparisons use greater than alone.

5. elif is checked in order

In an if/elif/else chain, Python checks conditions from top to bottom and chooses the first true branch. Later elif branches are not evaluated for execution after an earlier branch succeeds. The final else acts as a fallback when no preceding condition is true.

A common mistake places a broad condition before a narrow one, making the narrow branch unreachable. For example, `if x>=50` before `elif x>=80` means x=90 takes the first branch, not the higher-threshold branch. Arrange mutually intended bands in an order that matches the task.

6. Conditions can be combined with and

The Boolean operator and requires both conditions to be true for the entire expression to be true. A fictional eligibility test might require age>=13 and age<=16. A value inside the inclusive interval satisfies both comparisons.

A student should evaluate each subcondition separately before combining them. For age 12, the first comparison is false; for age 17 the second is false. Using `and` for a range check is different from using `or`, which could allow values outside the intended interval.

7. or requires at least one true condition

An expression such as n==2 or n==5 is True when n is either 2 or 5. It is not necessary for both comparisons to be true. In a programme, or can express allowed alternatives or several independent reasons for a branch.

A common syntax mistake writes n==2 or 5, which does not compare n to 5 as intended. Write complete Boolean conditions on both sides of the operator. The result of a logical expression follows Python’s evaluation rules; explicit comparisons make the intended meaning clearer.

8. not reverses a Boolean condition

The operator not reverses True and False. If available is False, then not available is True. In a decision, this can express absence or a condition that must not hold, but it should not be confused with numerical negation.

Parentheses help clarify the intended grouping. `not (x>5)` is true when x is five or less, provided x is a comparable number. A sentence saying ‘not greater than five’ is not the same as ‘less than five’ at the boundary where x equals five.

9. Indentation is part of the programme

Python uses indentation to define which statements belong to an if block or a loop. A line outside the indented block may execute after the branch even when the condition was false. A programme with misleading visual indentation is not just stylistically confusing; it can change execution.

For a written trace, draw an outline around each block. Then mark whether the condition causes that block to run. A misplaced assignment outside a loop can produce a different final total despite using the same numerical values as a correctly indented version.

10. A for loop iterates over an iterable

The structure `for i in range(4):` visits i=0,1,2,3. The body runs once per value under normal execution. The stop boundary of range is excluded, so a student should not include i=4.

A for loop can also iterate through the items of a list. For example, a loop over [3,6,9] visits each of those three values in order. A loop variable is a name for the current item or range value; it should not be confused with the number of times the body has already executed.

11. range can specify a start and step

range(1,5) produces 1,2,3,4. range(2,9,3) produces 2,5,8. The optional step changes the sequence of visited values, but the stop remains excluded. A zero step is invalid.

Predict the values before calculating an accumulator. If a loop adds i for each value in range(1,5), the total is 1+2+3+4 = 10. Guessing that the loop includes five creates an off-by-one error that can spread through later calculations.

12. while repeats while its condition is true

A while loop evaluates its condition before each iteration. If the condition is initially false, the body may not run at all. If the condition is true, the body executes and then the condition is checked again.

A useful example begins count=0 and repeats while count<4, incrementing count by one inside the loop. The body runs for count values 0,1,2,3, and the final count is 4. There are four iterations, not five, because the condition is false when count reaches four.

13. Termination must be explainable

A loop should make progress towards the condition becoming false when it is intended to terminate. A while loop that checks count<4 but never changes count can repeat indefinitely if count begins below four. Merely writing a syntactically valid loop does not make its behaviour correct.

Before executing a new loop, identify the loop variable, initial value, update rule and exit condition. Trace a few iterations by hand. If the state never changes in a way that can end the loop, review the design rather than running it and hoping it finishes.

14. Trace tables reveal logic errors

A trace table can record the value of a loop counter, an accumulator, the condition result and the output after each iteration. This makes state changes visible. For example, starting total=0 and adding 2,4,6 in a for loop leads to totals 2,6,12.

If the programme instead resets total to zero inside the loop, the final value will be wrong. The trace reveals the first incorrect state. A tutor should ask the student to justify each row instead of merely pointing to the last printed number.

15. Nested decisions need deliberate grouping

An if block may contain another if statement. The inner condition is tested only when execution reaches it. An inner else belongs to the appropriate if according to indentation, which can be visually confusing in a long example.

In a learning exercise, reduce nested code to a clear decision tree. First choose the outer branch, then evaluate the inner one if applicable. Do not evaluate an unreachable inner condition as though it were independent. Clear block boundaries make the intended path easier to explain.

16. Testing conditions should cover boundaries

A conditional that uses n>=10 differs from one using n>10 exactly at n=10. A loop with a range stop of five differs from one that includes five. Good test cases deliberately include thresholds, zero iterations, one iteration and a number just beyond the boundary.

Testing does not simply confirm that a typical value works. A correct programme must behave according to requirements at the places where the result could switch. This is why dry runs and carefully chosen boundary cases are a core part of reliable computing practice.

score = 76
if score >= 80:
    band = "A"
elif score >= 60:
    band = "B"
else:
    band = "C"
print(band)  # B

total = 0
for i in range(1,5):
    total += i
print(total) # 10

count = 0
while count < 4:
    count += 1
print(count) # 4

Twelve-stage Branch–Loop–Termination protocol

This original practice routine is designed for manual dry runs and is not an official marking rubric. It helps students decide which instructions execute, how state changes, what is printed, and whether an iteration has a valid stopping condition.

Stage 1 — Copy the initial state

Record every variable, its value and the relevant data type before the first condition or loop starts.

Stage 2 — Find the control-flow structure

Identify whether code follows a simple sequence, an if/elif/else chain, a for loop or a while loop.

Stage 3 — Mark the indentation

Draw the boundaries of each block and note which else belongs to which if. Indentation changes execution.

Stage 4 — Evaluate atomic comparisons

Work out each expression such as x>=5 or y==3 before combining conditions with logical operators.

Stage 5 — Combine Boolean conditions

Apply and, or and not precisely; use parentheses to make non-obvious grouping clear.

Stage 6 — Choose the first valid branch

In an if/elif/else chain, select the first true condition and skip later alternatives.

Stage 7 — List for-loop values

Write the values actually generated by range, remembering that its stop boundary is excluded.

Stage 8 — Check while before the body

A while condition is evaluated before each iteration. The body may execute zero times.

Stage 9 — Track loop updates

Record the counter, accumulator and any other modified variable after each iteration.

Stage 10 — Look for progress to termination

Identify which changed value can make the condition false and whether the update is sufficient.

Stage 11 — Record output at the right moment

Printing inside a loop may produce several messages; printing after the loop produces a value at completion.

Stage 12 — Test a boundary input

Use equality, zero iterations, one iteration or an input just beyond a threshold to verify the explanation.

Twelve original branch and loop worked cases

Worked case 1 — A true if condition

If x=7 and the branch condition is x>5, its indented body runs. A student should not also execute the alternative else body in the same if/else decision.

Worked case 2 — A false if condition

If x=4 and the condition is x>5, its body does not run. Statements after the if at the same indentation can still execute normally.

Worked case 3 — Equality at a boundary

For x=5, the condition x>=5 is True but x>5 is False. A single equals sign in the comparison can determine the branch selected.

Worked case 4 — The first true elif wins

For score=90, an if score>=50 branch placed before elif score>=80 captures the value. The later higher-threshold branch is not chosen, even though its comparison would have been true.

Worked case 5 — A correctly ordered band

For score=76, the chain if score>=80, elif score>=60, else chooses the middle branch. It checks the high band first, then the next inclusive threshold.

Worked case 6 — An and condition

The expression 13<=age and age<=16 is True for age 14, but False for 12 or 17. Both inequalities must hold.

Worked case 7 — An or condition

The expression n==2 or n==5 is True for 2 and 5 but False for 3. Writing n==2 or 5 would not express the intended pair of comparisons.

Worked case 8 — A not condition

For x=5, not (x>5) is True because x>5 is False. This does not mean x must be strictly less than five.

Worked case 9 — A normal for range

for i in range(4) visits 0,1,2,3, so a body that executes normally runs four times. Index four is excluded by the stop boundary.

Worked case 10 — A range with a step

range(2,9,3) supplies 2,5,8. A following value 11 would exceed the excluded upper boundary, so it is not included.

Worked case 11 — A finite while loop

With count=0 and while count<4: count+=1, the body executes four times. The final count is four because the next condition check is False.

Worked case 12 — An initially false while

With count=5 and while count<4, the body does not run even once. The condition is checked before the first possible iteration.

Twelve further execution traces

Worked case 13 — Adding a range

Starting total=0 and adding every i in range(1,5) produces 1+2+3+4=10. The excluded stop value five is not included in the accumulator.

Worked case 14 — A descending range

range(5,0,-2) yields 5,3,1. The negative step counts downward while the stop of zero is still excluded.

Worked case 15 — An empty positive-step range

range(5,2) yields no values under its default positive step. The body of a for loop over it is not executed.

Worked case 16 — List iteration

for item in [3,6,9] visits 3, then 6, then 9. The loop variable refers to the current element, not a zero-based index in this form.

Worked case 17 — Print inside versus outside

If print(count) is inside a while loop, it may print once per iteration. Move it outside at the same indentation level as while, and it executes after completion.

Worked case 18 — Count before updating

With count=0 and while count<3, print(count) followed by count+=1 displays 0,1,2. After the loop, count is 3. The displayed values are not the same as the final counter.

Worked case 19 — Update before printing

With the same condition but count+=1 before print(count), the displayed values are 1,2,3. A small change of statement order alters the visible output.

Worked case 20 — Halving to a limit

Starting n=20 and repeating n//=2 while n>1 yields successive n values 10,5,2,1. The body executes four times and the final comparison 1>1 is False.

Worked case 21 — A missing counter update

With count=0, while count<3 and no statement changing count, the condition remains true. The loop has no demonstrated termination. Such a programme should be corrected on paper before execution.

Worked case 22 — A nested decision

If an outer condition is False, an inner if contained only in that block is not reached. Evaluating the inner condition as if it were independent gives an incorrect execution trace.

Worked case 23 — A broad branch hides a narrow one

If x>=0 appears before elif x>=10, a positive x such as 20 enters the first branch. The more specific comparison is unreachable for such values.

Worked case 24 — Different types of error

Forgetting a colon after if is a syntax problem; omitting a loop counter update may be a logic problem; dividing by zero inside an executed branch produces a runtime error. Correct diagnosis guides the fix.

Connected explanations and practical investigations

A fictional class-capacity decision

Imagine a programme that reports whether a fictional tutorial room can seat a requested group. A capacity of 12 and group size 12 should be allowed if the requirement uses group_size<=capacity. Changing that condition to group_size<capacity would reject the exact boundary. A normal case with group size eight might not reveal the error.

A tutor can ask students to test group sizes 11, 12 and 13. The purpose is not to impose an education policy but to make the comparison visible. The same boundary technique applies to age bands, marks ranges and inventory thresholds. Every test should state which branch is expected and why.

Why elif ordering must be planned

A function assigning categories by threshold should test the most restrictive high threshold first when using a descending sequence of >= comparisons. For example, test >=80 before >=60, then use else as the remainder. If >=60 appears first, a score of 90 is captured by that branch and never reaches the >=80 test.

This is a logic mistake, not a mathematical misunderstanding of 90 or 80. The if/elif chain chooses the first true condition. The student should trace the control path and explain why later conditions are skipped, even if they would also be true in isolation.

A loop that counts and a loop that accumulates

A counter tracks how many iterations or records have been processed; an accumulator combines values, such as a running sum. They can coexist in a loop but answer different questions. For [3,6,9], the final count is three and the total is eighteen.

Confusing the two variables can produce a result that looks plausible but describes the wrong quantity. Write a trace table with separate columns for current item, count and total. Update each column at the moment the code changes it. This method makes the execution understandable without relying on a debugger.

How flowcharts express the same reasoning

A flowchart uses a decision shape for a condition and arrows for the next path. A loop is represented by a path that returns to an earlier test after relevant processing. The important skill is following which arrow is taken given the present values, not merely memorising the shapes.

For a threshold decision, trace the actual numerical condition and select its true or false path. For a loop, show the counter being updated before the arrow returns to the condition. A flowchart missing an update can conceal the same non-termination bug as a while loop missing an increment.

Why termination is a separate obligation

A while loop’s syntax may be correct even though it never ends. The student should identify the state used by the condition and show that the body can change that state towards a stopping value. With count starting at zero and increasing by one until it reaches four, progress is easy to explain.

More complicated loops might have several paths, some of which fail to update the counter. A convincing argument must consider each path that can repeat, not just the typical one. For exam exercises, it is often enough to trace the given finite case and flag the missing update when a deliberate trap is present.

Short-circuit evaluation and safe conditions

Python evaluates Boolean expressions from left to right and may avoid evaluating a second operand when the first already determines an and/or result. For instance, x!=0 and 10/x>2 is False without dividing by zero when x is zero. This is a useful broader programming behaviour.

It should not be used to justify unreadable or unsafe input logic. The intended condition should remain clear, and requirements should guide validation. In a school problem, make each comparison explicit before reasoning about the combined truth value and the selected branch.

A practical two-minute dry run

Ask a learner to trace count=0; total=0; while count<3: count+=1; total+=count. The updates give count=1 and total=1, then count=2 and total=3, then count=3 and total=6. The next condition is False, so the final state is count three and total six.

Now reverse the order of updating total and count, keeping the same initial state. The total would add the old count values 0,1,2 and become three. This contrast proves that statement order matters inside a loop, even when the variable names and termination condition are identical.

Connecting tests to software engineering

A programme should be checked with normal inputs, boundary values and conditions that can reveal an error. For a loop, test zero iterations, one iteration and several iterations. For an if/elif chain, test every branch, including the exact thresholds. A typical working example cannot establish that every possible path is correct.

Tutors can ask the student to identify the first unexpected trace-table row rather than make random code changes. Parents can support this by discussing a simple everyday sequence and what happens when a rule changes. The underlying skill is transferable: understand the decision, follow the state and verify the outcome.

Frequently asked questions

When does an if body execute?

Its indented statements run when the condition is True and execution reaches that decision.

Does elif check every condition?

It checks subsequent conditions only until the first true branch in the chain is selected.

Why does the order of elif branches matter?

A broad earlier condition may capture an input and prevent a more specific later branch from being reached.

What is the difference between and and or?

and needs both conditions to be true; or needs at least one true condition.

Does not mean a number is negative?

No. Boolean not reverses a truth value; numerical negation is a different operation.

Does range include its stop?

No. The stop is excluded even when the range has a specified start or step.

Can a for loop run zero times?

Yes. If the iterable contains no items, its body has no ordinary iterations.

Can a while loop run zero times?

Yes. A false initial condition prevents its body from executing.

Why can a while loop fail to terminate?

The state relevant to its condition may never change towards making that condition false.

What is the difference between a counter and an accumulator?

A counter counts events or iterations; an accumulator combines values such as a running total.

Why does indentation matter?

It identifies which statements are inside a branch or loop, changing when and whether they execute.

How do I check a long program?

Trace actual state changes and condition outcomes, then verify boundary cases and every accessible branch.

Final independent retrieval exercise

A fictional programme begins count=0 and total=0, then executes while count<4: count+=1; total+=count. The successive totals are 1, 3, 6 and 10, and the final count is four. The test count<4 becomes false only after the fourth update. Explain the four iterations in a trace table instead of simply reporting ten as the answer.

Next replace the while loop with for i in range(1,5): total+=i and compare the final total. It is also ten because the range supplies 1,2,3,4. The loops reach the same sum in this case, but their control mechanisms differ: one checks and updates an explicit condition variable, while the other visits the values of an iterable. Students should recognise that an equivalent output does not make the implementations identical.

Finally modify the condition to count<=4 and predict what changes, including the number of iterations and whether the final total remains ten. Under the same increment-first body, the loop now runs five times and the total becomes fifteen. This one-character boundary change is a powerful demonstration of why exact comparisons, correct updates and independent testing are indispensable to programming.

Official 2027 syllabus and connected eduKateSG learning

Consult the 2027 G3 Computing K349 syllabus (2.2.1, 2.3.6, 2.3.11 and 2.3.12). Related guides: Reference 361 — Software Engineering, Reference 368 — Python Numbers, the MOE V3.0 library and the immutable Clementi teaching reference.

Editorial review: 29 October 2026, Singapore. All cases and programmes are fictional. The lasting skill is to trace the actual execution path, record changing state and explain why the loop eventually stops.