In this article let us look at all of the comparison operators in Python and learn how to use them in our programs!
The first step in the journey towards mastery of any programming language is to learn about the various operators provided by that language and learn how to wield them. Python is no exception to this rule!
Even though the concepts might look simple, our brains are really good at understanding the concepts but not so good at remembering them!
The best trick to make our brains remember stuff is via active learning. By “active learning” I mean “doing”!!
So put on your coding hats, open your laptops and start experimenting and playing with the code shown in the examples as you read them!
The phrase “Practice Makes Perfect” did not survive so many centuries for no reason!
For those of you who came here just to refresh your memories, here is a cheat sheet!
Python Comparison Operators CheatSheet
There are 6 main comparison operators in Python, they are listed in Table-1 below
|!=||Not Equal to|
|>=||Greater than or Equal to|
|<=||Less than or Equal to|
The definition and usage of the comparison operators can be given as follows.
When we need to compare 2 objects in Python by value and get the comparison evaluated into a Boolean value, then we can use the comparison operators (==, !=, >, >=, <, <=)
If Python is your 1st programming language, the above table and definition might not tell you the whole story.
This article is specifically crafted keeping beginners in mind, so if you are feeling confused, forget that you ever read the paragraphs above, find a quiet place, focus for the next 10 to 15 minutes and read the rest of the article, then come back and read the answers above, I guarantee they will make more sense!
The rest of this article is focused on how to use each one of these operators in our Python programs with the help of some examples!
If you are not familiar with the “Python interpreter” then read the following side-note, else you can skip ahead to the next section!
Side Note: A Short Intro to the “Python interpreter“
The Python interpreter, simply put, is the command line prompt “>>>” you will get when you enter the “python3” command in your Linux or Mac terminal (“3” stands for Python version 3).
This way of using Python is also called using the “Interactive mode of the Python Interpreter”
$ python3 Python 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
If you are in windows, you can open up the interpreter app by opening the command prompt and by entering the following command
>python Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
Here you can play around with any Python program, one line at a time as shown below!
You can even use this environment like a calculator by typing the expression to be evaluated as shown below!
I remember the first time I played around with the interpreter, it was loads of fun! To this day, it is still my go-to calculator app!
Go ahead, play a little with the interpreter! You can always bookmark this page and come back to it later!
Alright if you are done playing around with the interpreter let us go back to the main focus of this article, which is about learning the comparison operators.
#1: The Equal to (“==“) Operator
Let us start by looking at the simplest of them all, the “Equal To” Operator.
First, let us see how the operator behaves in the Python interpreter.
>>> x = 1 >>> y = 2 >>> x == y False >>> y = 1 >>> x == y True
In this simple interactive session at the Python interpreter,
- the variable x is assigned a value of 1 and variable y is assigned a value of 2.
- When comparing for equality in line-3 using the x == y, the Python interpreter returns False
- Then y is reassigned to 1,
- the equality between x and y is checked again, and this time we get True.
Thus, the definition and usage of the “==” a.k.a the “equal to” operator can be given as follows
The “equal to” operator in Python (“==“) returns the boolean value True if the objects under comparison are equal to each other and returns False if the objects under comparison are not equal to each other.
Now that we have learned how the == operator works on the interpreter we have successfully mastered the 1st level which is understanding how the operator works.
Next, let us proceed to the next level and learn how to use it in our programs!
Consider the simple example below.
x = 10 y = 1 + 2 + 3 + 4 if x == y: print("1 + 2 + 3 + 4 is equal to 10") else: print("1 + 2 + 3 + 4 is not equal to 10")
A Challenge for you!
Before looking at the output, I want to challenge you to compute in your heads and predict what the code will print!
These thinking exercises will condition your brain to think like a programmer!
Are you ready? Okay, time for the explanation!
1 + 2 + 3 + 4 is equal to 10
Hope you got the answer right!
Here is a simple explanation of what the code does!
- We first assign the value 10 to the variable x, next we assign the value 1 + 2 + 3 + 4 to the variable y.
- Then we are checking if x and y are equal to each other using the operator “==”.
- Python will evaluate the value of 1 + 2 + 3 + 4 before assigning to y and hence the value 10 will be assigned to y.
- Now since x and y both contain the value 10, the statement x == y becomes True.
Hence the first print statement in line 5 of Example#2 above gets printed as output!
Sounds so simple right? Yup, Python is all about keeping things simple!
But this is not the end of the story!
Python is also designed to be flexible enough to make the “==” operator behave just the way we want it to!
I have written an entire article dedicated to this “==” operator where I have explained
- how to compare more than 2 values for equality and how Python internally accomplish this
- how the “==” operator is implemented behind the scenes
- how to make the “==” operator behave just the way we want it to on user defined classes and
- when to pick the “==”operator as opposed to the “is” operator in Python
You can find the article in the link below
Don’t worry if the above topics feel a bit too advanced, as the article above has been handcrafted and tailored specifically for beginners!
I suggest you first finish this article, to get your feet wet, and then proceed to the article in the link above and invest around 15 to 20 mins there to learn everything there is to know about the “==” operator in Python and achieve true mastery!
Alright, let us move on to the next operator on our list.
The Not Equal to(“!=“) Operator
This operator is very similar to the “==” operator, only that it does the opposite! The operator is used to check if the 2 objects under comparison are not equal to each other.
Let us start by seeing how the “!=” operator works in the Python interpreter’s command line
>>> x = 1 >>> y = 2 >>> x != y True >>> y = 1 >>> x != y False
Thus, the definition and usage of the “!=” a.k.a the “not equal to” operator can be given as follows
The “not equal to” operator in Python (“!=“) returns the boolean value “False” if the objects under comparison are equal to each other and returns “True” if the objects under comparison are not equal to each other.
Alright, time to write some Python program that uses the != operator!
a = 10 b = 1 * 2 * 3 * 4 if a != b: print("1 * 2 * 3 * 4 is not equal to 10") else: print("1 * 2 * 3 * 4 is equal to 10")
Another Code Reading Challenge!
Okay, now that you have read the code, time for a challenge!
Before reading on, try to answer this question!
What output do you think this code will print?
Alright, now let us see if you got the answer correct!
1 * 2 * 3 * 4 is not equal to 10
Yup, you guessed right!
1 * 2 * 3 * 4 is 24 and not 10 and hence a is not equal to b and hence we got the above output!
As with the “==” operator, we have an entire article dedicated to gaining mastery on the “!=” operator which you can find below.
In the article above, you can find answers to questions like
- since both “==” and “!=” can be used interchangeably, when to use which one?
- how is the “!=” operator implemented in python?
- what is the default behavior of “!=” operator in user defined classes? and
- how to make the “!=” operator behave the way we want it to for used defined classes?
Again, finish reading this present article first to get a general idea, then go to the article in the link above to achieve true mastery!
Okay, time to move on to the next operator on our list!
The Greater than(“>“) and Greater than or Equal to(“>=“) Operators
Let us again start by experimenting on the Python interpreter’s command line to develop our understanding of the “>” and “>=” operators
>>> x = 1 >>> y = 2 >>> y > x True >>> y = 1 >>> y > x False
- I have first assigned the value 1 to x and the value 2 to y
- Then I have used the “>” operator to check if y is greater than x and
- the Python interpreter returns True as expected!
- the variable y is made equal to 1. So now both x and y are holding the value 1,
- when the same check is performed to see if y is greater than x we get a False this time around.
This makes sense as 1 is not greater than 1, one is equal to 1!
Okay, this looks like an opportunity to play with the “>=” operator!
So let us see if y is “greater than or equal to” x!
>>> y >= x True >>>y 1 >>>x 1
Python says True as both the values of x and y are 1!
Consider the statement
You are either a DC fan or a Marvel fan.
If you like superheroes, then the above statement is probably true.
How do we know that is true?
Basically, we need to test 2 conditions
- You are a DC Fan
- You are a Marvel Fan
and if at least one of the above statements is true, then we can conclude that the original statement “You are either a DC fan or a Marvel fan” is True.
If you are not into superhero stuff, you probably don’t like DC and Marvel, then the above statement can be considered False (and come on, all superheroes are cool, give the movies a try!)
Similarly, with the “>=” operator we also have 2 statements
- “Greater Than” OR
- “Equal To”
If the comparison is “1 >= 1”
The 1st statement of “Greater Than” is not true as the value “1” is not greater than “1”
But the 2nd statement of “Equal To” is True, so since one of the 2 conditions is True, we get True!
Let us experiment a little bit more just to make the concept solid in our minds!
>>> 2 >= 1 True >>> 2 > 1 True >>> 2 == 1 False
In the example above the condition “Greater than” is True and the Condition “Equal To” is False
>>> 5 >= 5 True >>> 5 > 5 False >>> 5 == 5 True
In the example above, the condition “Greater Than” is False and the condition “Equal To” is True.
In computer science, these various combinations are usually presented in the form of a table, and we call it the “Truth Table”
|Condition-1||Condition-2||OR: Truth Value|
As you can see when we have 2 conditions combined with an “or”, if at least one of those is “True“, we get “True” as a result. The Greater than or Equal to Operator works in a similar manner.
Now that we have learned about how the “>” and “>=” operators work in python, let us learn how to make use of them in our programs!
appleDiameter = 8 orangeDiameter = 10 if appleDiameter > orangeDiameter: print("Apples are bigger than Oranges") else: print("Oranges are bigger than Apples")
In the example above, the condition in the if statement appleDiameter > orangeDiameter returns False as 8 is not greater than 10. Hence we get the output below
Oranges are bigger than Apples
The code is pretty self-explanatory so I leave it to you to figure out the logic. Remember to practice the art of “Thinking like a programmer!”
The above example showed you how to use the “<” operator with “if” statements, next let us take a look at another example, this time using the “greater than or equal to” operator and with “while” loops.
print('Countdown begins!') count = 5 while(count >= 1): print(count) count = count - 1 print('Happy New Year!')
The output of the above program looks like this
Countdown begins! 5 4 3 2 1 Happy New Year!
This operator is usually most useful in situations where we are counting down to some value as shown in the example above. Here, in the while loop, we are decrementing the count value from 5 to 1 and then printing “Happy New Year!”
SideNote: While statement:
If this is your first meeting with the “while” statement, While statements, simply put, repeat the code in the indented region under the while statement (lines 4 and 5 in our example) till the condition that is written next to the “while” keyword (count >= 1 in our example) becomes False.
Thus, the definition and usage of the “>” a.k.a the “greater than” operator can be given as follows
The “greater than” operator in Python (“>”) returns the boolean value True if the 1st object is greater than the 2nd object and returns False if the 1st object is not greater than the 2nd object.
and, the definition and usage of the “>=” a.k.a the “greater than or equal to” operator can be given as follows
The “greater than or equal to” operator in Python (“>=”) returns the boolean value False if the 1st object is less than the 2nd object and returns True otherwise.
The next logical question that comes to mind is
why not use “count > 0” instead of “count >= 1” and achieve the same result?
The answer is “Code Readability” i.e. the ease with which we can read the code.
While reading the code, the number “1” makes more sense as “0” is not intended to be in the output anyways. As you get more experience as a Python programmer, you will find that in some situations using the “>=” operator might make more sense than using the “>” operator and vice versa!
If you wish to gain mastery on the > and >= operators and learn how they are implemented and how to code them up for your own classes, we have an entire article dedicated to that, which you can find below.
In that article, I have explained
- how the greater than operators work on other data-types like strings
- how they are implemented in python
- default behavior of these operators in user defined class and
- how to customize the behavior of these operators in our own classes
Again, read this entire article first to get a general idea, then go to the article in the link above to achieve true mastery.
Next, let us look at the final pair of operators in our list, the “<=” operator and the “<” operator
Less than(“<“) and Less than or Equal to(“<=“) Operators
These 2 operators are very similar in meaning and usage to the greater than and greater than or equal to operators we saw in the previous section.
Let us again start our experimentation on how the “<” and “<=” operators work in the Python interpreter’s command line
>>> x = 1 >>> y = 2 >>> y < x False >>> y = 1 >>> y <= x True
No surprises here!
If you are not sure what is happening above, then remember to “Think like a programmer!”
Just like our previous operators, these 2 operators also return True or False depending on the comparison we are trying to do!
Let us also see a quick example program on how to use the less-than operator
lemonGrams= 100 orangeGrams = 150 if lemonGrams < orangeGrams: print("Oranges are heavier than Lemons") else: print("Lemons are heavier than Oranges")
Here we are comparing the weight of lemon vs orange. As expected the output will be
Oranges are heavier than Lemons
Next, let us see where and how to use the “less than or equal to” operator in our programs.
The “<=” operator is mainly used in situations where we need to
- do a comparison where the 1st value should not be greater than the first value.
- count up to some value.
Time for one last example!
Let us see how to use the “<=” operator to “count up” to something!
print('On 3!') count = 1 while count <= 3: print(count) count = count + 1 print('Start Coding!')
This will print
On 3! 1 2 3 Start Coding!
We could have changed line-3 in the example above to while count < 4 and achieved the same result, but the code is easier to read with the “<=” operator.
As you gain more experience writing programs, you will develop an intuitive sense of whether to use “<” and where to use “<=” in your given situation in your programs.
Thus, the definition and usage of the “<” a.k.a the “less than” operator can be given as follows
The “less than” operator in Python (“<“) returns the boolean value True if the 1st object is less than the 2nd object and returns False if the 1st object is not less than the 2nd object.
and, the definition and usage of the “<=” a.k.a the “less than or equal to” operator can be given as follows
The “less than or equal to” operator in Python (“<=”) returns the boolean value False if the 1st object is greater than the 2nd object and returns True otherwise.
As with all the other operators, if you wish to gain mastery on the < and <= operators, and learn how they are implemented internally in python and how to implement this functionality for your own classes, we have an entire article dedicated to that, which you can find below.
In that article, you can find answers to questions like
- how the less than operators work with string
- how the less than operators work with user defined classes
- when to use “>” instead of “<”
along with many more interesting questions and examples!
Where to go from here?
Now that we have got our feet wet and have looked at a simple overview of the comparison operators, our next step is to play around and practice these concepts till they sink in and become second nature!
Once you have reached that level, the next step is to go ahead and read all the individual articles that focus on each of these individual operators so that you can achieve true mastery. This extra step is what differentiates mediocre Python programmers from the masters of the language!
You can find all the individual articles mentioned during the course of this article in the following “Related Articles” section below.
Alright with that I will end this article!
I hope you found it useful, feel free to share this article with your friends and colleagues!