Relational Operators
Comparison operators, also called relational operators, compare two values and answer with a Boolean value: either True or False. They never change the values they look at — they just report how the two values relate to each other.
| Operator | Meaning | Question it asks |
|---|---|---|
== | equal to | are the two values the same? |
!= | not equal to | are the two values different? |
< | less than | is the left value smaller? |
<= | less than or equal to | is the left value smaller, or the same? |
> | greater than | is the left value larger? |
>= | greater than or equal to | is the left value larger, or the same? |
Every comparison reduces to a single True or False — never to the values themselves. A cinema hall has booked 87 of its 120 seats, so seats_booked < hall_capacity is True, seats_booked == hall_capacity is False and seats_booked != hall_capacity is True. The numbers themselves are untouched; the comparison only reports on them.
That result can be printed straight away, or stored in a variable. A variable holding a comparison is a Boolean variable: it stores True or False rather than a number or a string, ready to be used later in the program.
seats_booked = 87
hall_capacity = 120
# print a comparison to see its Boolean answer straight away
print(seats_booked < hall_capacity)
print(seats_booked == hall_capacity)
print(seats_booked != hall_capacity)
# or save the answer in a Boolean variable and use it later
full = seats_booked >= hall_capacity
print("Hall full?", full)Output:
True
False
True
Hall full? False
Either side of an operator can be a variable or a fixed value, and both sides can be variables. seats_booked < hall_capacity compares two variables, while seats_booked < 100 compares a variable with a value, and 87 != 120 compares two values directly. The operator sits between the two things being compared, with one on the left and one on the right.
The equals sign always comes second, so the inclusive tests are written <= and >=; typing =< or => is not valid and the program will not run. A single = is not one of the six operators either, because it assigns a value to a variable rather than comparing, so == is the one that asks whether two values are equal.
OCR GCSE Computer Science · Relational Operators
OCR GCSE Computer Science · Condition-Controlled Iteration