Logical and comparison operators allow us to build logical statements that evaluate to true or false. In programming we can evaluate logical statements and then perform different tasks depending on whether the logical statement is true or false. Often this allows us to perform a task under certain conditions. For example, sending an automated email between 8am and 5pm.

Suppose we were to make the following statement: *Your age is greater than 30.*

This statement is either true or false depending, of course, on your actual age. This is based on comparing your actual age to the number 30 to evaluate if the statement is true or false. In Python we do this by taking two values and placing a comparison operator between them that tells Python how we are trying to compare the values in order for it to evaluate the statement.

The comparison operators are:

== | Evaluates if the value on the left is equal to the value on right |

!= | Evaluates if the value on the left is not equal to the value on right |

> | Evaluates if the value on the left is greater than the value on the right |

< | Evaluates if the value on the left is less than the value on right |

>= | Evaluates if the value on the left is greater than or equal to the value on the right |

<= | Evaluates if the value on the left is less than or equal to the value on the right |

We use these comparison operators in Python to build conditional statements in the following way:

5 == 10

> False

5 != 10

> True

5 > 10

> False

5 < 10

> True

5 >= 10

> False

5 <= 10

> True

Logical operators allow us to join two or more logical statements together and evaluate the statement as a whole with the output depending on which logical operators used to join the statements together.

Let’s consider the statement we made above about your age and join this to another statement about you: *Your age is greater than 30 and you have 1 child.*

This statement contains two sub-statements that if evaluated independently might have two different results i.e. you are 30 but you have two children rather than one. In this case for the statement as a whole to be true then both logical sub-statements have to be true because we joined them using the word “and”. Therefore if you are 30 but have two children, the statement evaluates to false. However, if we had used the word “or” instead of “and”, then only one of the sub-statements would need to be true in order for the whole statement to evaluate to true and therefore as you are 30 then the statement as a whole is true.

This is the same in Python. We can use the logical operators “and”, “or” and “not” to join logical statements together to create larger and more complex statements for evaluation. We do this in the following way.

a = 10

b = 50

a == 5 and b > 20

b = 50

a == 5 and b > 20

> False

a == 5 or b > 20

> True

not(a == 5 and b > 20)

> True

Next