Menu

Relational Operators

Comparisons in conditions

A condition is the test that a selection statement or a loop uses to decide what happens next. You write it as a comparison, so it produces a Boolean result of True or False โ€” slices >= friends asks whether there is a slice of pizza for everyone at the table.

In Python, the comparison goes after the keyword that opens the statement, such as if, and it is answered at the moment the program reaches that line. The True or False is not printed and does not change any variable: it is used straight away to decide whether the code underneath runs.

How a condition decides

soil_moisture = 28
if soil_moisture < 40:
    print("Water the plants")
if soil_moisture > 70:
    print("Drain the soil")

Output:

Water the plants

The first condition is worked out when its line is reached: soil_moisture < 40 is True for 28, so the watering message is printed. The second condition is then asked separately, and soil_moisture > 70 is False, so its message is skipped. The comparison is written once but can give a different answer on another run, because the variable may hold a different value.

Loops use a condition in the same way: the same True or False comparison, checked as the loop runs. The loop structures themselves are covered in other subtopics, but the comparison inside them works exactly as it does in an if statement.

Practise this