IB COMPUTER SCIENCE | B2.3.2 Selection Structures

Lesson objective

Construct selection structures using if, else, Python elif and Java else if, with appropriate Boolean and relational conditions to control execution.

Learn

B2.3.2 | SELECTION STRUCTURES

01 | PROGRAMS NEED TO CHOOSE

A program should accept a booking only when places remain, show a different grade for different marks, or ask for correction when input is outside the allowed range. Executing every action unconditionally would not meet those objectives.

Selection chooses which block of instructions runs according to a condition. A condition has a logical result, True or False. The selected block is a branch.

This common SL/HL lesson constructs Python if/elif/else programs and reads the corresponding Java if/else if/else syntax. We will develop relational comparisons, Boolean combinations, nested decisions and tests that expose incorrect branch choices.

02 | A SIMPLE IF: AN OPTIONAL ACTION

temperature = 31
if temperature > 30:
    print("High temperature")
print("Reading recorded")

The condition asks whether the current temperature is greater than 30. If true, execute the indented warning. If false, skip it. The final print is outside the if block and runs on either normal route.

For 31, output High temperature then Reading recorded. For 25, output only Reading recorded. A simple if does not require an else when no alternative action is needed.

An if checks once when reached. It does not automatically keep monitoring temperature; repeated checking requires a loop or another event/call.

03 | INDENTATION DEFINES THE PYTHON BLOCK

places = 2
if places > 0:
    print("Places available")
    print("You can request a booking")
print("End of check")

Both indented statements belong to the true branch. The unindented End of check lies after the selection. Changing indentation can change which outputs occur.

Use a colon after the condition and consistent indentation for the body. A missing colon or invalid indentation can prevent parsing; valid but unintended indentation can instead create a logic error.

When tracing, follow the actual indentation rather than the visual intention suggested by a comment.

04 | IF/ELSE: TWO ALTERNATIVES

places = 0
if places > 0:
    print("Booking possible")
else:
    print("Workshop full")

Exactly one of the two blocks is selected on a normal execution of this construct. The else means “otherwise” and has no condition of its own.

This example assumes places is a valid non-negative availability count. Negative stored availability would indicate another problem; simply calling it full would not establish that the data is valid.

Use if/else when the requirement defines two mutually exclusive outcomes, rather than two independent actions that might both be needed.

05 | RELATIONAL OPERATORS

Operator Meaning Example / result
< Less than 4 < 5 is True
<= Less than or equal 5 <= 5 is True
> Greater than 5 > 5 is False
>= Greater than or equal 5 >= 5 is True
== Equal in value 5 == 5 is True
!= Not equal in value 5 != 5 is False

Python = assigns a value, while == compares values. Do not replace a comparison with assignment. != means not equal; <> is not the Python 3 operator.

Compare values of the intended types. Numeric 12 and text "12" are not the same representation; convert input appropriately before using numerical order comparisons.

06 | A BOOLEAN CAN BE THE CONDITION

has_permission = True
if has_permission:
    print("Permission recorded")
else:
    print("Permission needed")

A condition can use a Boolean variable directly instead of always writing a relational expression. has_permission already holds True or False.

Do not confuse the Boolean False with the nonempty string "False". Python treats that string as true in a truth test. Parse or compare permitted responses deliberately rather than assuming bool(input_text) understands a yes/no word.

Use meaningful Boolean names so the decision reads clearly. A Boolean result can be assigned before the if when a long expression needs explanation.

07 | ELIF: CHOOSE ONE OF SEVERAL BRANCHES

marks = 85
if marks >= 80:
    print("Distinction")
elif marks >= 50:
    print("Pass")
else:
    print("Developing")

Python tests conditions from top to bottom. The first true branch runs, and the remaining elif/else alternatives are skipped. For 85, only Distinction is printed, even though 85 is also at least 50.

For 65, the first test is false and the second true, so output Pass. For 40, both tests are false and else outputs Developing. These are fictional classroom categories, not official IB grade boundaries.

The second branch does not need marks < 80 here: reaching it already establishes that the earlier comparison was false.

08 | ORDER OVERLAPPING THRESHOLDS CORRECTLY

marks = 85
if marks >= 50:
    print("Pass")
elif marks >= 80:
    print("Distinction")
else:
    print("Developing")

This prints Pass. Every mark at least 80 also satisfies the earlier at-least-50 test, so the Distinction branch is never selected. The program runs, but its branch order violates the stated category rule.

Check the most restrictive overlapping threshold first, or use non-overlapping ranges with a clearly justified order. Do not assume adding another elif automatically makes the intended outcome reachable.

Test values in every category and exactly on each boundary. A test with 65 alone would not reveal this error.

09 | INDEPENDENT IFS CAN BOTH RUN

marks = 85
if marks >= 80:
    print("Distinction")
if marks >= 50:
    print("Pass")
else:
    print("Developing")

The two if statements are separate selections. For 85, both true blocks run, producing Distinction then Pass. The else belongs to the second if, not to the whole visual group.

Independent if statements are useful when several actions may apply, such as checking both a high temperature and low battery. An elif chain is useful when only one category should be selected.

Choose the structure from the objective, not because one uses fewer lines.

10 | INTERACTIVE: SEE WHICH CONDITIONS ARE TESTED

Compare three supplied grade programs using a whole-number mark from 0 to 100. Predict the outputs before checking. The trace distinguishes tested conditions from skipped alternatives; it does not execute arbitrary source code.

Try 49, 50, 79, 80 and 85. Ask whether the program meets the one-category objective and whether a branch is unreachable.

11 | AND: BOTH REQUIREMENTS MUST HOLD

age = 14
in_age_range = age >= 12 and age <= 17
if in_age_range:
    print("Age condition met")
else:
    print("Outside the age range")

and is true only when both operands are true. The range includes 12 and 17 because both comparisons allow equality.

Python also permits 12 <= age <= 17 as a chained comparison. Writing age >= 12 and <= 17 is invalid because the second comparison lacks its left operand.

Choose AND for an interval that requires both a lower and an upper bound. age >= 12 or age <= 17 would accept every ordinary numeric age because at least one of those inequalities always holds.

12 | OR: AT LEAST ONE ALTERNATIVE

day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("Weekend")
else:
    print("Weekday")

or is true when at least one operand is true, including when both are true. It does not mean “exactly one” unless the expression explicitly implements that rule.

Write both comparisons. if day == "Saturday" or "Sunday": is a common bug: the nonempty string "Sunday" is truthy, so the expression is true even for a weekday.

For a small set of accepted values, membership such as day in ["Saturday", "Sunday"] is another Python expression with the same intended decision here.

13 | NOT: INVERT A BOOLEAN CONDITION

suspended = False
if not suspended:
    print("No suspension block")
else:
    print("Access blocked")

not reverses the truth value. If suspended is False, not suspended is True. Name the original condition clearly so the negation is easy to read.

“Not suspended” alone may be necessary but insufficient for access. Other requirements can still apply. Avoid treating the absence of one blocking condition as proof that all admission requirements are met.

14 | BOOLEAN COMBINATIONS AT A GLANCE

A B A and B A or B
False False False False
False True False True
True False False True
True True True True

not False is True, and not True is False. Use this table to reason about a combination, then connect the Boolean names to the real requirement.

In Python, comparisons bind more tightly than not, then and, then or. Use parentheses to make the intended grouping explicit rather than relying on memory when a rule is complex.

15 | COMBINE ALTERNATIVES WITH A BLOCKING RULE

For a fictional workshop, accept a person if they are aged 12–17 inclusive OR are a registered member, but never accept someone currently suspended. The membership alternative permits other ages under this stated teaching rule.

age = 10
member = True
suspended = False
in_age_range = age >= 12 and age <= 17
eligible = (in_age_range or member) and not suspended
if eligible:
    print("Eligible")
else:
    print("Not eligible")

The parentheses group the two positive alternatives before applying the suspension block to both. Without correct grouping, one alternative might bypass the blocking rule.

The inputs are assumed to be a valid age and actual Boolean flags. This is a fictional eligibility calculation, not a complete identity, security or permissions system.

16 | INTERACTIVE: BUILD THE BOOLEAN DECISION

Use the workshop rule above. The activity calculates the component comparisons and combined results, then shows the selected branch. Try a suspended member to check that the blocking rule applies to both alternatives.

in_age_range = age >= 12 and age <= 17
eligible = (in_age_range or member) and not suspended
if eligible:
    print("Eligible")
else:
    print("Not eligible")

17 | SHORT-CIRCUIT EVALUATION

text = ""
if len(text) > 0 and text[0] == "A":
    print("Starts with A")
else:
    print("Empty or starts differently")

Python and evaluates its right operand only if the left operand is truthy. The first check is false for empty text, so text[0] is not evaluated and no IndexError occurs.

or skips its right operand if the left is truthy. This can support useful guards, but do not rely on a skipped expression to perform a necessary state change.

Reversing the guard order can fail: text[0] would be attempted before the nonempty check. In Java, && and || provide short-circuit logical combinations; their single-character counterparts have different rules.

18 | NESTED SELECTION: A CHOICE WITHIN A CHOICE

logged_in = True
can_edit = False
if logged_in:
    if can_edit:
        print("Edit option available")
    else:
        print("Read-only option")
else:
    print("Sign in first")

The inner selection is reached only through the outer true branch. With these values, the output is Read-only option. When logged_in is False, the inner condition is not tested.

Indentation identifies which else belongs to which if in Python. Nesting is useful when outcomes need different messages at different stages.

A combined condition can sometimes simplify nesting, but it may lose distinct feedback. Ensure a rewrite preserves all required outcomes rather than only matching one example.

19 | VALIDATE BEFORE CLASSIFYING

raw = "85"
try:
    marks = int(raw)
except ValueError:
    print("Enter a whole-number mark")
else:
    if marks < 0 or marks > 100:
        print("Mark outside 0 to 100")
    elif marks >= 80:
        print("Distinction")
    elif marks >= 50:
        print("Pass")
    else:
        print("Developing")

The category chain assumes the mark is in range. Checking invalid values first prevents 140 from being treated as a valid distinction mark.

Use OR for invalid-outside-range: below the minimum OR above the maximum. Use AND for valid-inside-range. The two requirements differ.

Conversion handling and range validation are separate; a converted integer can still be invalid for the domain.

20 | JAVA: IF, ELSE IF AND ELSE

public class SelectionExample {
    public static void main(String[] args) {
        int marks = 85;
        if (marks < 0 || marks > 100) {
            System.out.println("Invalid mark");
        } else if (marks >= 80) {
            System.out.println("Distinction");
        } else if (marks >= 50) {
            System.out.println("Pass");
        } else {
            System.out.println("Developing");
        }
    }
}

Java uses else if rather than Python elif, parentheses around conditions and braces for blocks. The first matching branch still determines the outcome in the chain.

Java Boolean combinations use && for AND, || for OR and ! for NOT. Its Boolean literals are true and false, with lowercase initials. Python uses and, or, not, True and False.

21 | JAVA STRING COMPARISONS NEED CARE

public class DayExample {
    public static void main(String[] args) {
        String day = "Saturday";
        boolean weekend = day.equals("Saturday") || day.equals("Sunday");
        if (weekend) {
            System.out.println("Weekend");
        } else {
            System.out.println("Weekday");
        }
    }
}

For Java String content, use an appropriate content comparison such as equals. == on references tests whether they refer to the same object, so it is not the general way to compare text contents. This example assumes day is non-null.

Python str == compares values. Do not transfer every language’s operator rule without checking its meaning for the types involved.

22 | WORKED PROGRAM: A BOOKING DECISION

def booking_message(raw, available, has_permission):
    try:
        requested = int(raw)
    except ValueError:
        return "Enter a whole number"
    if requested <= 0:
        return "Request must be positive"
    elif not has_permission:
        return "Permission required"
    elif requested > available:
        return "Not enough places"
    else:
        return "Request can be accepted"

print(booking_message("3", 5, True))
print(booking_message("3", 5, False))
print(booking_message("6", 5, True))

The results are Request can be accepted, Permission required and Not enough places. The order also chooses the reported reason when several conditions would reject the same request.

The function only reports a decision; it does not save a booking or deduct places. available and has_permission are assumed valid supplied state. A complete system needs appropriate state updates and concurrency/error handling.

23 | CONSTRUCT YOUR OWN CATEGORY PROGRAM

Create a function classifying a valid integer battery percentage: 0–19 Low, 20–79 Ready and 80–100 High. Reject values outside 0–100. Return one message for every input, and test the boundaries.

Reveal one possible solution
def battery_status(percent):
    if percent < 0 or percent > 100:
        return "Invalid"
    elif percent >= 80:
        return "High"
    elif percent >= 20:
        return "Ready"
    else:
        return "Low"

for value in [-1, 0, 19, 20, 79, 80, 100, 101]:
    print(value, battery_status(value))

Assume integer arguments; validating an arbitrary argument type is outside this small task. The expected messages are Invalid, Low, Low, Ready, Ready, High, High, Invalid. Using a loop here simply runs the same selection for several tests.

24 | TEST EACH PATH AND ITS BOUNDARIES

Test purpose Grade examples Why
Lower boundary −1,0 Separate invalid input from valid minimum.
Pass threshold 49,50,51 Check the equality operator and adjacent values.
Distinction threshold 79,80,81 Expose wrong threshold order or strict comparison.
Upper boundary 100,101 Separate valid maximum from excessive input.
Independent flags Both true; both false; each alone Check AND/OR/NOT combinations.
Nested outer false Not logged in Confirm the inner block is skipped.

When comparing two program versions, inspect the conditions evaluated and the selected outputs. One correct result cannot establish that every branch is reachable or correct.

25 | COMMON MISTAKES

Mistake Correction
Use = for comparison Use == for value equality in these examples.
Put the broadest overlapping threshold first Order or separate ranges so required categories remain reachable.
Use separate ifs for one exclusive category Use an appropriate if/elif/else chain.
Write x==A or B State both comparisons or use suitable membership.
Use OR for both bounds of an inside range Require lower AND upper bound.
Treat a string "False" as Boolean False Parse/validate responses deliberately.
An if repeats until its condition changes An if chooses once when reached; looping is separate.
All languages compare strings with identical semantics Use the chosen language’s content-comparison rules.

26 | CONSTRUCT AND EXPLAIN THE BRANCHES

A strong construct answer supplies working code for the stated objective, with correct indentation or braces, conditions, branch ordering and outcomes. State input assumptions and keep invalid values out of ordinary categories.

Explain an outcome by substituting current values into the tested conditions, noting which later alternatives are skipped. The next lesson adds looping structures so selected actions can repeat.

MATCH THE SELECTION IDEA

Terminology

Terminology

Selection

Choosing which block executes according to a condition.

Condition

An expression evaluated for a logical/truth result to control a choice.

Branch

One possible execution route through selection.

Boolean

A logical True/False value in the examples.

if

A construct executing its block when the condition is true.

else

The otherwise branch when prior alternatives in the construct are not selected.

elif

Python’s additional condition in an exclusive selection chain.

else if

Java’s form for an additional conditional alternative.

Relational operator

An operator comparing values, such as < or >=.

Equality comparison

Testing whether values are equal, using == in these Python examples.

Inequality comparison

Testing not equal, using !=.

AND

A logical combination requiring both operands to be true.

OR

A logical combination true when at least one operand is true.

NOT

A logical negation reversing a truth value.

Truth table

A table listing logical results for combinations of inputs.

Short-circuit evaluation

Skipping a logical operand when the result is already determined by an earlier operand.

Guard condition

A check that prevents an unsafe or inappropriate later evaluation.

Nested selection

A selection construct inside another selected block.

Exclusive chain

A construct selecting the first true branch and skipping later alternatives.

Independent if statements

Separate decisions whose true blocks can both execute.

Threshold

A boundary used to classify or decide.

Inclusive boundary

A boundary whose equality value is accepted, such as >=12.

Overlapping conditions

Conditions that can be true for some of the same inputs.

Unreachable branch

An outcome that cannot be selected under the preceding tests.

Precedence

The rules grouping operators when parentheses do not specify grouping.

Parentheses

Grouping that makes an intended logical expression explicit.

Validation

Checking inputs against the problem’s allowed rules.

Truthy value

A value Python treats as true in a condition, such as nonempty text.

Content comparison

Comparing the data represented by text rather than Java reference identity.

Boundary test

A test at or near a decision limit.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe a simple if?
2. Which distinguish Python operators?
3. Which describe an if/elif/else chain?
4. For mark85, which statements apply?
5. Which represent an inclusive age range12–17?
6. Which describe OR and NOT?
7. Which avoid the day-comparison bug?
8. Which describe short-circuit guards?
9. Which describe the workshop rule?
10. Which describe Java syntax accurately?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Construct a Python if/else showing whether places remain.

2. Construct a descending grade chain for the stated fictional categories.

3. Trace the ascending grade chain for85.

4. Distinguish independent if statements from an exclusive chain.

5. Construct an inclusive age-range condition.

6. Explain why day=="Saturday" or "Sunday" is incorrect.

7. Construct the workshop eligibility rule.

8. Trace the workshop rule for age10, memberTrue, suspendedTrue.

9. Explain the nonempty-string short-circuit guard.

10. Construct a nested login/edit selection.

11. Describe the corresponding Java multi-branch structure.

12. Construct tests for the battery-status task.

CONSTRUCT IT | ACTIVITY ADMISSION

Construct a program for a fictional activity: accept if places remain AND the student has permission; otherwise distinguish Full from Permission required. Include a case where both rejection reasons apply and state which one your ordering reports first. Test all four combinations of the two Boolean conditions.

Reveal an approach

Test places <= 0 first for Full; elif not has_permission for Permission required; else accept. This gives Full when both reasons apply. Alternatively, nesting can preserve the same ordering. A different first-reason policy needs an explicit agreed rule; do not treat the code order as automatically the only valid policy.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B2.3.2 Selection Structures is coming soon. Complete the matching task and written questions in your exercise book.