Courses / Mathematics I
Programming Elements

Conditionals and Boolean Logic

Mathematics I 232 words Free to read

Making Decisions

Programs make decisions using conditional statements. An if statement runs code only when a condition is true; an if/else chooses between two paths; else if chains mutually exclusive cases. The condition is a boolean expression, evaluating to true or false.

Conditions rely on comparison operators to produce booleans:

OperatorMeaningExample
==Equalx == 5
!=Not equalx != 5
<, >Less / Greaterx < 10
Pitfall: Never confuse = (assignment: store a value) with == (comparison: test equality). Writing if (x = 5) assigns 5 instead of testing it.
One condition, two branches -- then the sign that breaks it

Boolean Logic

Booleans combine using logical operators, matching propositional logic:

OperatorSymbolRule
and&&True if both are true
or\|\|True if at least one is true
not!Negates the boolean

Operator precedence and parentheses control evaluation order. For safety, use parentheses: (x > 0) and (x < 10).

Languages use short-circuit evaluation: in A and BA \text{ and } B, if AA is false, BB is skipped. This prevents runtime errors, allowing safe guards like checking if a list has items before inspecting its contents.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes

Programming Elements