sciandu
Computer science

Computer science

Conditionals

How programs make decisions: if, then, else.

What you need first

You make hundreds of decisions every day: if it rains, you take an umbrella, otherwise you don't. When the alarm rings, you get up. Programs work the same way: they check a condition and then decide what happens next. That is exactly what you will explore now.

If, then, else

A conditional, also called an if statement, is a fork in the road of your program. It has three parts: the condition itself (if), a branch for when the condition is true (then), and a branch for when it is false (else). The program always follows only one of the two paths, never both at once.

Decision switch
Temperature12 °C
if t ≤ 0: scarf and hat
else if t < 20: jacket
else: T-shirt
At 12 °C: jacket
Try it: change the values and watch which branch the program takes.

Conditions are comparisons

A condition is almost always a comparison between two values: is one number greater than another? Smaller? Or exactly equal? Every comparison has exactly one answer: true or false. The comparison 7 greater than 5 is true, the comparison 3 equals 4 is false. Watch out for the borderline case: greater than means strictly greater, less than means strictly less. That is why 9 less than 9 is false, because 9 is exactly as big as 9. With that answer, the program knows which branch to take.

Checking several cases in a row

Often there are more than two possibilities. Then the program checks several conditions one after another: if the first one is true, its branch runs and the rest is skipped. If not, the next condition gets its turn, and so on. The order matters: the first condition that is true always wins.

Exercises

0 of 6 solved

Time to try it yourself. You can't break anything, every attempt counts.

What does the comparison 5 greater than 3 give?

A program says: if the temperature is greater than 25, then pool, else cinema. The temperature is 20. What happens?

A program says: if x is greater than 10, output 1, else output 0. x is 7. What is the output?

Match each part of a conditional to its meaning.

if
then
else

A program says: if x equals 5, output x plus 1, else output x minus 1. x is 5. What is the output?

Every comparison between two values has exactly one of two possible answers: true or .

Where this leads