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:
| Operator | Meaning | Example |
|---|---|---|
== | Equal | x == 5 |
!= | Not equal | x != 5 |
<, > | Less / Greater | x < 10 |
Pitfall: Never confuse=(assignment: store a value) with==(comparison: test equality). Writingif (x = 5)assigns 5 instead of testing it.
Boolean Logic
Booleans combine using logical operators, matching propositional logic:
| Operator | Symbol | Rule |
|---|---|---|
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 , if is false, is skipped. This prevents runtime errors, allowing safe guards like checking if a list has items before inspecting its contents.