Python comparison operators

Jayashree domala
3 min readSep 17, 2020

--

Guide to understand the working of comparison operators in Python

Comparison operators help us to compare variables and output a boolean value.

To know more about booleans in python, read the article here.

Below shown is a table demonstrating the different operators along with their role and example.

Types of comparison operators (Source: Google)

Equality

>>> 85 == 85
True
>>> 17 == 16
False
>>> 8 = 3
File "<ipython-input-3-1f3f47bc060f>", line 1
8 = 3
^
SyntaxError: can't assign to literal

Using two equal signs is necessary because if you use a single equal sign, it will give an error. This happens because a single equal sign is used to assign values to variables.

>>> 'python' == 'python'
True

While comparing strings, capitalization also counts.

>>> 'python' == 'Python'
False

While comparing, the data type is also taken into account.

>>> 45 == '45'
False

In the case of comparing floating-point and integers, the data type is not taken into account.

>>> 5 == 5.0
True

Inequality

>>> 67 != 67
False
>>> 57 != 67
True

Greater than

>>> 17 > 19
False
>>> 14 > 2
True

Lesser than

>>> 6 < 9
True
>>> 6 < 0
False

Greater than or equal to

>>> 8 >= 8
True
>>> 94 >= 65
True
>>> 14 >= 68
False

Lesser than or equal to

>>> 4 <= 4
True
>>> 4 <= 9
True
>>> 56 <= 12
False

Chaining comparison operators

Logical operators can be used to combine comparisons. The keywords used for chaining are as follows:

1) and

2) or

3) not

‘and’ keyword

Suppose you want to check two conditions and make sure both are true, ‘and’ is used.

>>> 14 < 15
True
>>> 15 < 16
True
>>> 14 < 15 < 16
True
>>> 14 < 15 > 16
False
>>> 14 < 15 and 15 < 16
True
>>> 14 < 15 and 15 > 16
False
>>>("python" == "python") and (3 == 4)
False

‘or’ keyword

Suppose you want to check two conditions and make sure at least one is true, ‘or’ is used.

14 < 15 or 15 > 16
True
14 > 15 or 15 > 16
False

‘not’ keyword

It returns the opposite boolean.

>>> 45 == 45
True
>>> not(45 == 45)
False
>>> 1 < 0
False
>>> not(1 < 0)
True

Refer to the notebook here.

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Jayashree domala
Jayashree domala

Written by Jayashree domala

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.