Courses / Mathematics I
Programming Elements

Conditionals and Boolean Logic

Mathematics I 302 words Free to read

Making Decisions

Programs make decisions with conditional statements. An if statement runs a block of code only when a condition is true; an if/else chooses between two paths; else if chains several mutually exclusive cases. The condition is a boolean expression — one that evaluates to true or false — so this is the propositional logic of Unit 1 made executable.

Conditions are built from comparison operators== (equal), != (not equal), <, >, <=, >= — each producing a boolean. A frequent beginner error is confusing = (assignment: store a value) with == (comparison: test equality); they are entirely different operations.

Booleans combine with logical operators, exactly the connectives of Unit 1:

So (x > 0) and (x < 10) tests "x is between 0 and 10." Operator precedence and parentheses matter here as with arithmetic; when in doubt, parenthesise to make the grouping explicit.

Many languages use short-circuit evaluation: in A and B, if A is false the whole expression is already false, so B is never evaluated (and dually for or). This is not just an optimisation — it lets you write safe guards like "if the list is nonempty and its first element is positive," where checking the second part would fail if the first were false.

Common pitfall: using = (assignment) where == (comparison) is meant. if (x = 5) assigns 5 to x (and is usually always-true or an error), whereas if (x == 5) tests whether x equals 5. The single-versus-double equals distinction — command versus question — is one of the most common bugs, and the two do completely different things.

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
Start Mathematics I free

Programming Elements