Courses / Computer Science I
Programming I

Conditionals and Logical Branching

Computer Science I 289 words Free to read

Making Decisions

A program that always does the same thing is not very useful. Conditionals let it choose a path based on whether a condition is true. The basic form is if: if a boolean condition holds, run one block; optionally, an else block runs when it does not.

if temperature > 30:
    print("hot")
else:
    print("not hot")

The condition is a boolean expression — one that evaluates to true or false. Comparison operators produce booleans: == (equal), != (not equal), <, >, <=, >=. A frequent bug is confusing == (comparison) with = (assignment).

Boolean operators combine conditions. and is true only when both sides are true; or is true when at least one side is true; not flips a boolean. Their truth tables are worth memorizing:

ABA and BA or B
TTTT
TFFT
FTFT
FFFF

Conditions can be chained with else if (or elif) to test several cases in order; the first matching branch runs and the rest are skipped. Many languages also short-circuit: in A and B, if A is false the whole thing is already false, so B is never evaluated — which matters when B has side effects or could error.

Common pitfall: writing = (assignment) where you mean == (comparison) in a condition. if x = 5 tries to assign rather than compare, and in many languages is a bug or error. The condition of an if must be a comparison or boolean, using ==, not a single =.

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 Computer Science I free

Programming I