Unit 11.1A · Term 1

Boolean Logic & Branching

Programs make decisions by evaluating conditions as True or False. Comparison and logical operators build those conditions, while if, elif and else decide which path the program follows.

Learning Objectives

  • 11.1.1.7 Apply logic operations to Boolean variables
  • 11.1.1.8 Use logical operations AND, OR, NOT in selection structure
  • 11.1.1.9 Implement the branching algorithm according to the flowchart

Selection / Branching

Craig'n'Dave — the three basic programming constructs. Selection begins at about 00:59.

Conceptual Anchor

The Traffic Light Analogy

A traffic light is a branching algorithm: IF the light is green → go; ELIF it is yellow → slow down; ELSE → stop. Each decision is based on a condition that evaluates to True or False.

STOP
SLOW
GO
if green: GO
elif yellow: SLOW DOWN
else: STOP

Comparison Operators

==equal to
!=not equal to
>greater than
<less than
>=greater or equal
<=less or equal
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater or equal 5 >= 5 True
<= Less or equal 5 <= 3 False

Comparison Lab

Evaluate the comparison before choosing.

Logical Operators: AND, OR, NOT

and

Both conditions must be True

A and B is True only when A and B are both True.

or

At least one must be True

A or B is True when A is True, B is True, or both are True.

not

Reverse a Boolean value

not True becomes False, and not False becomes True.

Operator Meaning True when… Example
and Both conditions must be True A is True AND B is True (x > 0) and (x < 100)
or At least one condition is True A is True OR B is True, or both (x == 0) or (x == 1)
not Inverts the Boolean value The original condition is False not (x > 10)

Truth Table

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

Boolean Logic Explorer

A
B
A and B
A or B
not A
not B

Compound Boolean Predictor

Work through NOT, then AND, then OR unless parentheses change the order.

Boolean Precedence

not highest of these logical operators
and evaluated after NOT
or lowest of these logical operators

Use parentheses when clarity matters

(a or b) and c is not always the same as a or (b and c). Parentheses make the intended grouping clear.

English → Boolean Expression

Age is at least 18 AND the user has ID.
age >= 18 and has_id
It is Saturday OR Sunday.
day == "Saturday" or day == "Sunday"
It is NOT raining.
not is_raining

                            
Choose the Boolean expression that matches the sentence.

if / elif / else

if condition_1:
    block_A

elif condition_2:
    block_B

else:
    block_C
if condition_1

If this is True, Python executes block A and leaves the chain.

elif condition_2

This is checked only if all previous conditions were False.

else

This runs only when every previous condition was False.

First True Branch Rule

In one if / elif / else chain, Python executes the first branch whose condition is True, then skips the rest of that chain.

Branching Simulator — Grade Classifier

Why Order Matters

Problematic order

if score >= 60:
    print("D")
elif score >= 70:
    print("C")
elif score >= 80:
    print("B")
elif score >= 90:
    print("A")

For score = 95, the very first condition is already True, so this prints D.

Correct descending thresholds

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

Start with the most restrictive/highest threshold.

if / if / if vs if / elif / else

Separate if statements

x = 10

if x > 0:
    print("positive")

if x > 5:
    print("greater than 5")

Both conditions are checked, so both messages can be printed.

One if/elif chain

x = 10

if x > 0:
    print("positive")

elif x > 5:
    print("greater than 5")

The first condition is True, so the elif is not checked.

Flowchart → Code

START
Oval Start / End
INPUT
Parallelogram Input / Output
PROCESS
Rectangle Process / assignment
?
Diamond Decision / condition
Arrow Flow direction
Start Input age age ≥ 18? No Yes "Minor" "Adult" End
age = int(input("Age: "))

if age >= 18:
    print("Adult")
else:
    print("Minor")

Flowchart translation rule

A decision diamond becomes a Boolean condition. Its Yes/True and No/False arrows become alternative code paths.

Flowchart Path Tracer

Follow only the path selected by the current input. Change the number and trace again.


                                

Press Next step to move through the algorithm.

Flowchart → Code Challenge

Choose the Python code that matches the flowchart logic.

Compound Conditions vs Nested if

Compound condition

if age >= 18 and has_id:
    print("Access granted")

Compact when both conditions are part of one decision.

Nested if

if age >= 18:
    if has_id:
        print("Access granted")

Useful when the second decision belongs inside the first branch.

Equivalent only in suitable situations

These two examples grant access under the same simple condition, but nested structures are more flexible when each level needs its own else or additional processing.

Extension: Python chained comparisons
# Standard form age >= 18 and age <= 65 # Python also allows: 18 <= age <= 65

Worked Examples

Choose an example:

Short-Circuit Logic

False and ...

The full AND expression is already known to be False, so Python may skip evaluating the remaining part.

True or ...

The full OR expression is already known to be True, so Python may skip evaluating the remaining part.

Boolean & Branch Error Lab


                            
Identify the most important problem.

Pitfalls & Common Errors

= vs ==

= assigns a value. == compares two values. Use if x == 5:, not if x = 5:.

Forgetting the colon

if, elif and else headers end with :.

Indentation matters

Python uses indentation to define a block. Use consistent indentation, conventionally four spaces.

Incorrect elif ordering

In threshold problems, place more restrictive conditions first. Otherwise an earlier broad condition may capture the value.

Incomplete AND condition

if x > 5 and < 10: is invalid. Write if x > 5 and x < 10:.

x == 5 or 10

Do not write x == 5 or 10 when you mean two comparisons. Write x == 5 or x == 10.

Style tip

If a variable is already Boolean, prefer if is_logged_in: instead of if is_logged_in == True:.

Pro-Tips for Exams

Exam Strategy

  • When tracing a flowchart, follow only one path at a time for the current input.
  • In an if/elif/else chain, stop after the first True branch.
  • For and, one False operand is enough to make the whole expression False.
  • For or, one True operand is enough to make the whole expression True.
  • Logical precedence: not before and before or.
  • Draw a small truth table when a compound Boolean expression is difficult to trace.
  • A flowchart diamond represents a decision condition.

Graded Tasks

Remember

State the purpose of ==, !=, and, or and not.

Understand

Complete the truth table for A and (B or not C) for all combinations of A, B and C.

Understand

Explain the difference between three separate if statements and one if/elif/else chain.

Apply

Write a Boolean expression that is True when age is between 18 and 65 inclusive and has_id is True.

Apply

Write a program that reads a year and determines whether it is a leap year: divisible by 4, but not 100, unless also divisible by 400.

Apply

Implement a flowchart that classifies a temperature as Hot (>30), Warm (>20), Cool (>10), or Cold.

Analyze

Trace this program for x = 15 and explain why only one branch runs: if x > 10 and x < 20: ... elif x > 5: ... else: ...

Create

Create a quiz program with three True/False questions, count the score and output Excellent / Good / Fair / Fail.

Exam Practice

Q1: State the output and explain which branch is executed. [3]

x = 15 if x > 10 and x < 20: print("A") elif x > 5: print("B") else: print("C")
Reveal marking points
Output: A x > 10 is True and x < 20 is True. Therefore the first condition is True. The first branch runs and the elif/else branches are skipped.

Q2: Write a Boolean expression that is True when age is between 18 and 65 inclusive. [2]

Reveal marking points
age >= 18 and age <= 65 Python extension: 18 <= age <= 65

Q3: Convert the following logic into Python. [4]
Input temperature → if temperature > 30 output "Hot" → otherwise if temperature > 20 output "Warm" → otherwise output "Cool".

Reveal marking points
temperature = float(input("Temperature: ")) if temperature > 30: print("Hot") elif temperature > 20: print("Warm") else: print("Cool")

Q4: Explain why x == 5 or 10 is not the correct way to test whether x is 5 or 10. [2]

Reveal marking points
The second part, 10, is not a comparison. Write: x == 5 or x == 10.

Self-Check Quiz

Eight quick checks Click each answer to reveal
1. What is True and False?
Click to reveal answer
2. What is True or False?
Click to reveal answer
3. What is not True?
Click to reveal answer
4. What is the difference between = and ==?
Click to reveal answer
5. What is the logical-operator precedence order?
Click to reveal answer
6. In one if/elif/else chain, what happens after the first True branch?
Click to reveal answer
7. Which flowchart shape represents a decision?
Click to reveal answer
8. How should you write “x is 5 or x is 10”?
Click to reveal answer