Comparison Statements and Boolean Logic#
Learning Objectives#
Use Python comparison operators to compare objects.
Use logical statements to perform multiple comparisons at once.
Prerequisites#
Comparisons in Python#
Python has a number of different ways in which it can compare objects, variables or just numbers. These can be very useful both for simple tasks (“Does H2O have a higher molecular weight than NH3”) and more complex ones (“How do we know that this peak in an IR spectrum is above the baseline noise?”)
In computing, the term Boolean means a result that can only have one of two possible values: True or False. Using comparison operators (listed in the below table) we can compare two values. The output is a Boolean (either True or False).
Operator |
Definition |
Example |
|---|---|---|
== |
is equal to |
|
! = |
is not equal to, ≠ |
|
> |
is greater than |
|
< |
is less than |
|
>= |
is greater than or equal to, ≥ |
|
<= |
is less than or equal to, ≤ |
|
is |
are the same object |
|
in |
the object contains another object |
|
Running a statement, such as:
3 == 5
will return one of two outputs: True or False. In this case, this statement is False.
Although both the greater than (“>”) and less than (“<”) mathematical operations are identical to those used in standard mathematical notation, the greater than or equal to operation (”≥”) is written with two characters, >=. This is the same for the is not equal to (”≠”) symbol, written instead as !=, or the is equal to symbol, written as ==.
Be especially careful with ==. We know from our understanding of variables that = is used in Python to assign values to variable names, and so we cannot use it here, hence using double equal signs.
Comparison operators work for both numerical data types in Python (integers and floats), but also work for some non-numerical data types (such as strings and lists).
Comparing numbers: floats and integers
The most basic use for comparisons is numerically, using integers or floats. You can compare integers to floats.
4 < 2
Returns False
5.1 >= 3.6
Returns True
4 == 4.0
Returns True
This is pretty obvious, but it becomes especially useful with number stored in variables.
If we have a very long piece of code where we are doing lots of maths, we probably won’t know the exact value stored inside every variable, especially if its a long float, so instead we can refer to it by its variable name.
num_1 = 53.09127281
num_1 > 10
Returns True
num_1 = 53.09127281
num_2 = 53.09283821
num_1 == num_2
Returns False
Comparing other data types: strings and lists
As well as comparing numbers, you can use comparison operators on strings and lists.
Note that all parts of the string (including order of characters) and all parts of a list (including the order of elements and data type) need to be identical for the == operation to return True.
The operators >, <, >=, and <= comment only on the length of the list.
"CH4" == "CH4"
Returns True.
"NH3" == "H3N"
Returns False. The numerals are not in the same order.
["2", 3, 4] == ["2", 3, 4.0]
Returns True. All items in the two lists are equivalent.
["helium" , "neon" , "argon"] == ["helium" , "argon" , "neon"]
Returns False. The items in the lists are in a different order.
["helium" , "neon" , "argon"] == ["helium","neon","argon"]
Returns True. The items in the lists are the same, and in the same order.
Comparing different data types
Most different data types, even if they have the same contents, will always yield a == comparison of False. An exception is floats and integers, which can be compared.
"5" == 5
Returns False. They are two different data types. The first is a string, the second is an integer.
5 == 5.0
Returns True. Floats and integers can be compared.
Identifying identical objects using is
The comparator == identifies if two objects have the same contents (in the same order), but what if we wanted to distinguish if they are also exactly the same object (i.e. rather than just looking the same, they are actually the same ‘behind the scenes’)? For this, we can use is:
x = ["N", "H", 3]
y = ["N", "H", 3]
x is y
Returns False. Although these two lists contain the same chemical formula in the same order, they have been assigned to two different variables, and are currently two separate instances of variables that happen to look the same. They are not the same object according to Python.
However:
y = ["N", "H", 3]
x = y
x is y
Returns True. We have specifically reassigned the variable x to the value of y, and so now the is comparison is True.
Finding contents using in
in has two uses - you will see it come back in another way when we do for loops. In this context, in checks if a certain object is contained within a string or list.
"O" in "H2O"
Returns True
masses = [1.008, 12.011, 15.999]
14.007 in masses
Returns False
Chaining together comparisons
You can also chain together these comparisons, but you need to be careful you don’t get confused!
a = 1
b = 2
c = 3
a != b != c
Returns True because none of those values are the same. However, it is NOT checking the comparison between a and c. You could run the following:
3 != 2 != 3
Which would return True, because it is only comparing the adjacent numbers.
Exercise: Obtain a True output
In the comparisons in the code below, replace each dash with different comparison operators to get a True output.
num_nitrogen = 7 num_fluorine = 9 num_nitrogen -- num_fluorine num_fluorine -- num_nitrogen num_fluorine -- num_nitrogen num_fluorine -- num_fluorine num_nitrogen -- num_nitrogen
Click to view answer
num_nitrogen = 7
num_fluorine = 9
num_nitrogen <= num_fluorine
num_fluorine != num_nitrogen
num_fluorine > num_nitrogen
num_fluorine is num_fluorine
num_nitrogen == num_nitrogen
Any operators that return True in these contexts are correct.
Exercise: Test similarity
On the following two variables, use Python comparisons to test the following:
Are the two calculated values for the Rydberg constant the same?
Which calculated value for the Rydberg constant is larger?
# Two different calculates values for the Rydberg constant rydberg_1 = 10973731.56815712 # m^-1 rydberg_2 = 10973731.58615712 # m^-1
Click to view answer
The two values are not the same. You can check this using:
rydberg_1 == rydberg_2
Which will return
False.rydberg_2is larger. You can test this by using either<or>.
Boolean logic operators#
Can we make multiple comparisons at the same time - i.e. to check if a number is within a certain range of bounds? Yes, and for this, we need Boolean operators - these are written as words but still make comparisons between two things: and, or and not.
Operator |
Definition |
Example (x and y are comparisons) |
|---|---|---|
and |
Both instances must be True to return True, otherwise will return False |
|
or |
Either instance can be True in order to return True. If both instances are False, will return False. |
|
not |
If the Boolean value of the instance is True, the program will return False. Essentially inverts the logic. |
|
Remember, logic operators are used to perform multiple comparisons at once! For example:
a == b and c > d
Using and
When considering a and b, where a and b are individual comparisons, a and b must both be True for the overall result to be True.
z = 2
z < 3 and z > 1
The first part of the statement z < 3 is True, and the second part z > 1 is also True. Since both parts are True, the overall result will output True.
However, if the test was instead:
z < 3 and z != 2
The output would be False, since the second statement z != 2 is now False. A True and a False outputs a False.
If both parts of the statement were False, the output would also be False.
Using or
When considering a or b, where a and b are individual comparisons, only one of the two must be True for the whole statement to be True. If neither are True, the whole statement will be False.
z = 2
z < 3 or z > 0.1
Returns True as both statements are True.
The test:
z < 3 or z !=2
Also returns True, even though the second statement is False. Only one of the two statements needs to be True to return True.
In order to get an output False, both statements must be False:
z > 3 or z != 2
Using not
Finally, not is slightly different. It should be used before a comparison statement, i.e. (not a == 2), and ‘inverts’ the True or False behaviour. If a statement was True, not will make it False, or vice versa.
not True
Returns False, and vice versa.
z = 2
not z <= 2
Returns False, as the comparison is True.
z = 2
not z > 3 or z != 2
Returns True, as the output from the or statement is False.
# Checking a perovskite does not contain chromium
perovskite = "CH3NH3PbBr3"
"Cr" not in perovskite
Returns True.
Understanding order of comparisons
Watch out! Python evaluates operators according to a strict order: maths and comparison operators first, then logical operators (and, or, not). If you are getting error messages, try bracketing your ‘not’ and other logical operators to give them precedence. Try the following lines with and without the brackets and try to understand the order of operations.
False == (not True)
(True or False) == False
True == (True and False) == False
Make sure to use round brackets when clarifying the order of operations. Other types of brackets are used to define other data types and may result in errors.
Exercise: Logical outputs
What is the logical output of this piece of code?
w = "tungsten" w == "neon" or w == "iron" or w == "bismuth" or w == "tungsten"
Click to view answer
The answer is True. Because each comparison is separated by or, only one of them has to be True for the overall output to be True. since the last comparison, w == "tungsten" is True, the overall output is True.
Further Practice#
Question 1#
Predict the logical output of this code, then write it out and run it to see if you are correct. How could we change it to get the opposite answer?
a = 1
b = 2
c = 3
d = a < c
a < b <= c and d == False
Click to view answer
When working out logic, it is worth going through step by step.
a < b is True. b <= c is True. Therefore a < b <= c is True.
The variable d is set as a < c. a < c is True, therefore d = True. Therefore, in the second statement, since d is True, the comparison d == False is False.
When using an and statement, both statements must be True to return True. Since the first statement is True and the second is False, the overall output is False.
If you want to get the opposite answer, you need to make both statements True. You can do this by changing the second statement to d == True.
Learning Outcomes#
In this lesson we have learned:
How to make comparisons between numbers and variables of different data types, getting Boolean True or False statements
How we can use Boolean operators such as
andandorto compare if multiple statements are True or False in different combinations.
Summary#
Python’s comparison operators are
==,!=,>,<,>=, and<=.Python’s logic operators are
and,or, andnot.
Operator |
Definition |
Example |
|---|---|---|
== |
is equal to |
|
! = |
is not equal to |
|
> |
is greater than |
|
< |
is less than |
|
>= |
is greater than or equal to |
|
<= |
is less than or equal to |
|
is |
are the same object |
|
and |
Both instances must be True to return True, otherwise will return False |
|
or |
Either instance can be True in order to return True. If both instances are False, will return False. |
|
not |
If the Boolean value of the instance is True, the program will return False. Essentially inverts the logic. |
|
You can chain statements together, but be careful to work in order and obey the order Python evaluates operators.
Python evaluates operators in the order: maths and comparisons, then logic. You can clarify your intentions by using round brackets.