Search

# Python Comparison Operators

Updated: Aug 21, 2020 ## Python Comparison Operators

In this article, we will be learning about Comparison Operators in Python. These operators will allow us to compare variables and output a Boolean value (True or False).

If you have any sort of background in Math, these operators should be very straight forward.

First we'll present a table of the comparison operators and then work through some examples: Let's now work through quick examples of each of these.

## Equal

Example:

```
2==2

```

Output:

```
True

```

Example:

```
1==0

```

Output:

```
False

```

Note that == is a comparison operator, while = is an assignment operator.

Example:

```
2 != 1

```

Output:

```
True

```

Example:

```
2 != 2

```

Output:

```
False

```

Example:

```
2 > 1

```

Output:

```
True

```

Example:

```
2 > 4

```

Output:

```
False

```

Example:

```
2 < 4

```

Output:

```
True

```

Example:

```
2 < 1

```

Output:

```
False

```

Example:

```
2 >= 2

```

Output:

```
True

```

Example:

```
2 >=  1

```

Output:

```
True

```

## Less than or Equal to

Example:

```
2 <= 2
```

Output:

```
True

```

Example:

```
2 <= 1
```

Output:

```
False

```

Great! Go over each comparison operator to make sure you understand what each one is saying. But hopefully, this was straightforward for you.

Next, we will cover chained comparison operators.

## Chained Comparison Operators

An interesting feature of Python is the ability to chain multiple comparisons to perform a more complex test. You can use these chained comparisons as shorthand for larger Boolean Expressions.

Now we will learn how to chain comparison operators and we will also introduce two other important statements in Python: and and or.

Let's look at a few examples of using chains

Example:

```
1 < 2 < 3

```

Output:

```
True

```

The above statement checks if 1 was less than 2 and if 2 was less than 3. We could have written this using an and statement in Python:

Example:

```
1<2 and 2<3
```

Output:

```
True

```

The and is used to make sure two checks have to be true in order for the total check to be true. Let's see another example:

Example:

```
1<3>2

```

Output:

`True`

The above checks if 3 is larger than both of the other numbers, so you could use and to rewrite it as:

Example:

```
1<3 and 3>2
```

Output:

```
True

```

It's important to note that Python is checking both instances of the comparisons. We can also use or to write comparisons in Python. For example:

Example:

```
1==2 or 2<3
```

Output:

```
True

```

Note how it was true; this is because, with the or operator, we only need one or the other to be true. Let's see one more example to drive this home:

Example:

```
1==1 or 100==1

```

Output:

```
True

```