AQA 7517, section 4.1.1.4
A relational operation compares two values and gives a Boolean result, either True or False. Relational operations are what selection and iteration use to decide what happens next.
The six operators
| Meaning | Python | Example | Result |
|---|---|---|---|
| Equal to | == |
5 == 5 |
True |
| Not equal to | != |
5 != 5 |
False |
| Less than | < |
3 < 7 |
True |
| Greater than | > |
3 > 7 |
False |
| Less than or equal to | <= |
7 <= 7 |
True |
| Greater than or equal to | >= |
3 >= 7 |
False |
age = 17
print(age >= 18) # False
print(age != 18) # True
print(age == 17) # True
Watch out: = and == are different. A single = is assignment, which stores a value. A double == is a comparison, which asks whether two values are equal. Writing if score = 10: is an error in Python, and in some other languages it silently assigns the value instead.
Using comparisons in selection and iteration
The condition in an if statement or a while loop is a relational expression:
password = input("Password: ")
if password == "open sesame":
print("Welcome")
else:
print("Access denied")
count = 0
while count < 5:
count = count + 1
Comparing different kinds of data
Relational operators work on more than numbers.
print("apple" < "banana") # True: compared in character code order
print("Zebra" < "apple") # True: capital letters have lower codes
# Strings are compared character by character
print("10" < "9") # True
print(10 < 9) # False: numbers are compared by value
Strings are compared one character at a time using their character codes. That is why "10" < "9" is True: the first characters are "1" and "9", and "1" has the lower code. This is a common source of bugs when numbers are read in as strings.
Watch out: don't test two floating point numbers for exact equality. 0.1 + 0.2 == 0.3 is False, because the values are stored as binary approximations. Instead check that the difference is very small, for example abs(a - b) < 0.000001.
Worked example
Task: a theme park charges by age. Children under 5 are free, 5 to 15 pay £10, and everyone 16 or over pays £15. Write the decision.
age = int(input("Age: "))
if age < 5:
price = 0
elif age <= 15:
price = 10
else:
price = 15
print("Price:", price)
Walk through it for an age of 15. 15 < 5 is False, so the first block is skipped. 15 <= 15 is True, so the price is 10. The <= matters: using < here would charge a 15-year-old £15, a boundary error.
Check yourself
What does 10 != 10 evaluate to?
False, because the two values are equal.
Give the difference between = and ==
= assigns a value to a variable. == compares two values and gives True or False.
Why might "100" < "20" be True?
Strings are compared character by character. The first characters are "1" and "2", and "1" comes first in the character set, so the comparison is True even though the number 100 is bigger than 20.
Write a condition that is true when x is between 10 and 20 inclusive
x >= 10 and x <= 20 (Python also allows 10 <= x <= 20).