In this article let us learn about the “>” and “>=” operators in Python with the help of some examples and learn how to make use of this operator the same way the pros do!
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 cheatsheet!
Python’s “>” and “>=” Operators: CheatSheet
|>||to see if 1st object is greater than the 2nd object||x > y||is x greater than y?|
|>=||to see if 1st object is greater than or equal to the 2nd object||x >= y||is x either greater than y or equal to y?|
What is > in Python?
The ‘>’ operator, pronounced as “greater than”, is used to compare 2 objects and returns True if the 1st object is greater than the 2nd object and returns False otherwise
What is >= in Python?
The ‘>=’ operator, pronounced as “greater than or equal to”, is used to compare 2 objects and returns True if the 1st object is greater than the 2nd object or if the 1st object is equal to the 2nd object and returns False otherwise.
In other words, the “>=” operator returns False if the 1st object is less than the 2nd object, returns True otherwise.
An example is worth 1000 words, so here is one for you!
>>> 5 > 3 True >>> 2 > 4 False >>> 4 >= 4 True
- In line-1 we ask “is 5 greater than 3?”, and Python says True
- In line-4 we ask “is 2 greater than 4?”, and Python says False
- In line-7 we ask “is 4 greater than or equal to 4?” and Python says True as number on either side of the “>=” operator are equal in this case.
The 2 objects under comparison are not just limited to numbers, it can be strings or lists or even some special user-defined classes. Intrigued by the idea of calling one string “greater than” another? Read on! I promise you will learn a thing or 2 as we have merely scratched the surface!
I have divided this article into 3 levels as shown below.
- Level#1: Beginner
- Level#2: Intermediate
- Level#3: Pro
Hence don’t worry if you have an ‘incomplete’ sort of feeling after reading the cheatsheet above, as this article has been handcrafted to take you through the journey of learning from beginner to pro in just about 15-20 minutes and the cheatsheet above is just to get your feet wet!
Here is a short intro to the Python Interpreter for complete beginners. If you are already familiar with the interpreter, how to launch and use it, you can safely skip this side-note!
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.
Let us start our learning journey at Level#1 with a couple of examples!
LEVEL#1 (BEGINNER): Play with the “greater than” (>) and “greater than or equal to” (>=) operators one line at a time in the Python Interpreter
Let us have another look at the example in the cheatsheet
>>> 5 > 3 True >>> 2 > 4 False >>> 4 > 4 False >>> 4 >= 4 True
In this simple session at the Python interpreter,
- In line-1 we ask “is 5 greater than 3?”, and Python says True
- In line-4 we ask “is 2 greater than 4?”, and Python says False
These 2 comparisons are pretty straightforward. Let’s take a look at line-7, here
- we ask “is 4 greater than 4?”, and Python says False .
- That is because the numbers on both sides of the “>” operator are both equal, and hence the one on the left is not greater than the other one on the right.
and in line-10
- we ask “is 4 greater than or equal to 4?” and Python says True.
- That is because, the numbers on both sides of the “>=” operator are equal and we are checking for “greater than” or “equality” using the “>=” operator.
Hope you are getting the idea behind these operators.
The above examples are super easy, let us have a look at a more complicated one and see how these comparison operators work on strings!
>>> 'cat' > 'elephant' False >>> 'dog' > 'bear' True >>> 'cat' >= 'cat' True
Challenge for you!
Before looking at the explanation, take a minute and try to guess what is happening here for strings.
If you have figured it out, congratulations! If not, here is a clue for you!
Clue: Experiment with single-letter strings!
I am guessing you have figured it out by now!
And, yes the answer is string makes use of lexicographical order to determine which one is greater! (Lexicographical order is just a fancy name for Alphabetical order, the order in which the words are printed in a dictionary!)
The logic used in the comparisons depends on the way the operator is implemented in the given class. In the built-in string class “Alphabetical order” is chosen as the logic by which we can determine which string is greater than the other.
Let us take a look at another simple example of comparing 2 strings.
>>> str1 = "apple" >>> str2 = "banana" >>> str1 > str2 False >>> str2 = "apple" >>> str2 >= str1 True
- we assigned the string “apple” to the variable str1 and
- the string “banana” to the string str2.
- In line 3 above we are comparing the variables str1 and str2 using the “>” operator and the python interpreter prints out False as expected (remember apple comes before banana in dictionaries!).
- In line 5 we have reassigned the variable str2 to “apple” and we are doing the “>=” comparison this time. As expected, we get True as the answer this time around!
Alright, now that we have seen some examples of how to use “>” and “>=” operators in the Python interpreter environment we have successfully completed LEVEL#1!
The time has come to use these operators in actual programs!
LEVEL#2: Gain mastery by using the “greater than” (>) and “greater than or equal to” (>=) operators in Python programs!
Take a look at the following python program
Don’t feel intimidated to read code, at first it can be tough but sooner than you realize you will be reading code like you read plain English!
# get user inputs numHoursFB_string = input("please enter the number of hours you spend on Facebook per day: ") numCodingHours_string = input("please enter the number of hours you spend coding per day: ") # convert to integers numHoursFB_int = int(numHoursFB_string) numCodingHours_int = int(numCodingHours_string) # compare the user inputs and give a suggestion if numCodingHours_int > numHoursFB_int: print("You have a going to be a great programmer very soon!") else: print("You really need to waste greater time on FB and code more!")
The example above is pretty self-explanatory.
We get 2 user inputs,
- the number of hours spent on social media like Facebook and
- the number of hours spent coding
Since the user inputs come as strings,
- we convert them to integers using the built-in int() function and then
- we make a comparison of these 2 values and give some suggestion to the user!
Running the program will give us an output like this!
please enter the number of hours you spend on Facebook per day: 25 please enter the number of hours you spend coding per day: 1 You really need to waste greater time on FB and code more!
Looks like using too much Facebook gave 2 hours extra per day to the person who took this test!
Alright enough jokes about social media, let us get back to the article!
On a side note, while programming in any language, we must always be prepared for any random input from the user! In other words, don’t expect the user to always act sane and be ready for some insane inputs like shown below!
please enter the number of hours you spend on Facebook per day: ten please enter the number of hours you spend coding per day: five
This is a whole other advanced topic, which is covered in detail in the article shown below.
Exceptions in Python: Everything You Need To Know!
I suggest you to read this one later on, when your Python is good enough to write simple programs!
Next, let us see how to use the “>=” operator in a program!
print("Count down!") num = 5 while (num >= 1) print(num) num = num - 1 print("Go Python!")
Count down! 5 4 3 2 1 Go Python!
You might be thinking why not use the “>” operator and write the same program like this!
print("Count down!") num = 5 while (num > 0) print(num) num = num - 1 print("Go Python!")
This will give the same exact output
Count down! 5 4 3 2 1 Go Python!
Why use “>=” when we have “>”
The answer is readability!
We wish to print 5 to 1, then the reader of your code will find it easier to digest your code if you use the numbers 1 and 5 in your code! Using “0” just makes things unnecessarily complicated!
To give you another example
age_string = input("Please enter your age: ") age_integer = int(age_string) if age_integer >= 18: print("Hope you make a good choice for the upcoming elections!") else: print("You cannot vote in the upcoming elections")
If we had used the “>” operator here then we should have used the number 17 instead of 18, which, I hope you agree, does not feel right in this situation!
Okay, I hope now you understand the need for having both the “>” and “>=” operators!
And with that, you have successfully completed level#2 of this article!
Let go into the uncharted territory of level#3 and gain mastery over these operators!
LEVEL#3: Become a Pro and gain full control of the “greater than” (>) and “greater than or equal to” (>=) operators and make them dance to your will!
Bravo if you have made it this far to Level#3!
You really have a hunger for knowledge! Keep it up and you will become an expert python programmer very soon!
At this level let us take things to the highest possible level and learn how python implements the “>=” operator internally and see how we can modify this behavior to make python dance to our wills!
How the “>=” and “>” operators are implemented in Python
Before starting to learn how “>” and “>=” operators are implemented inside of python, let us first learn a little bit about objects and methods in Python.
- everything like integers, strings, lists etc are Objects and
- all objects have some methods you can call to do some cool things with objects of a particular kind.
A good analogy would be
“methods” are like “dance moves” which a particular dancer (a given object) can do!
For example, consider the simple example below.
>>> string1 = "Hello Inventor!" >>> string1.swapcase() 'hELLO iNVENTOR!'
Here the swapcase() method is used to make all uppercase letters into lowercase and vice versa!
If you wish to know what are all the methods, you can type the following command into the python interpreter.
The screenshot below shows the usage of the help() command with the str type object
If you scroll a bit yourself, you will find yourself looking at a method named gt() and another one named ge() as shown in the screenshots below.
Let us try to understand what these methods do!
>>> a = 20 >>> b = 30 >>> a.__gt__(b) False >>> a.__ge__(b) False >>> b = 20 >>> a.__ge__(b) True
As you can see from the example above, both these methods take another object as an argument (the variable b in our case) and compare both of them and return either True or False.
- gt stands for ‘greater than’ and
- ge stands for ‘greater than or equal to’
So in essence, whenever we use the operator “>” in our code, python translates that to the form as shown above before executing the code!
a > b Becomes a.gt(b)
a >= b Becomes a.ge(b)
You might be thinking at this point “But what is the use of learning this detail?“
Say you have your own class, which you wish to give to your friends are colleagues, and you have your own logic of comparing 2 objects. Then if you want the “>” and “>=” operators to work on your classes, you need to implement the gt() and ge() methods in your own class.
Let us see how to do the same in the next section.
What is the default behavior of “>” and “>=” operators on User defined classes
According to Python documentation, the “>” and “>=” operators are not implemented by default on user-defined classes.
Let us see a simple fruit class as shown below.
class fruit(): def __init__(self, name, price_kg): self.name = name self.price_kg = price_kg
The above class has 2 attributes “name” and “price_kg” and a constructor init() to set these attributes.
Let us play with this fruit class by creating some objects on the Python interpreter
>>> apple = fruit("apple",10) >>> mango = fruit("mango",20) >>> apple > mango Traceback (most recent call last): File "<input>", line 1, in >module> apple > mango TypeError: '>' not supported between instances of 'fruit' and 'fruit'
We have made 2 objects: apple and mango, with apple being priced at 10 bucks per kg and the mango being priced at 20 bucks per kg.
When we do some comparisons, all hell breaks loose and we are left with a strange message!
This message basically means that the “>” operator is not implemented in the fruit class.
Let us see what happens if we use the “>=” operator!
>>> apple >= mango Traceback (most recent call last): File "<input>", line 1, in >module> apple >= mango TypeError: '>=' not supported between instances of 'fruit' and 'fruit'
The comparison fails one more time, with the exact same error message.
Okay, Python, I get it, you don’t know how to do this, stop throwing errors at us!!
Next, let us see how to solve this problem!
How to implement the ‘>’ and ‘>=’ operators in user defined classes
Assume we are fruit sellers. When comparing 2 fruits, the only thing fruit buyers are interested in is the parameter “price per kg”.
Let us expand the fruit class by including the gt() and ge() methods as shown below.
class fruit(): def __init__(self, name, price_kg): self.name = name self.price_kg = price_kg def __gt__(self, b): return (self.price_kg > b.price_kg) def __ge__(self, b): return (self.price_kg >= b.price_kg)
Now, the fruit class still has the same 2 attributes “name” and “price_kg”. But we have 3 methods,
- the constructor init()
- gt() and
- ge() methods to implement the behavior of the fruit class
Let us play with this fruit class now in the Python interpreter!
>>> peach = fruit("peach", 10) >>> kiwi = fruit("kiwi", 20) >>> mango = fruit("mango", 20) >>> kiwi > peach True >>> kiwi > mango False >>> kiwi >= mango True
As you can see this time, the “>” and “>=” operators finally work the way they are supposed to!
Peach and Kiwi have different prices and we get False, while Kiwi and mango have the same price and hence we get “True“!
I hope you understood how to define the behavior of “>” and “>=” operators for your own classes!
If you did then bravo!
You have successfully mastered these operators in Python!
There are some more operators in Python which act very similar to our greater than operators in terms of implementation and usage. Since you have already learned everything there is to know about the “>” and “>=” operators, you already know everything to know about some more operators too!
These are the 4 other comparison operators like our “>” and “>=” operators:
- < : Less than
- <= : Less than or Equal to
- == : Equal to
- != : Not Equal to
All these operators are implemented and used very similar to the way we use “>” and “>=” operators.
We have written a separate article explaining each of them using examples, please check them out in the link below!
Where to Go from Here
I suggest first playing a bit more with these “>” and “>=” operators just to get some practice.
Once you are done, the next obvious step would be to go and master the other operators! You can find the articles in the next section. I guarantee you can complete the next 4 comparison operators in one-fourth the time and energy as you have already learned the secret sauce!
If you have made it till the end, then congratulations and keep up this habit of finishing what you start, that is the one habit that differentiates winners from losers, and you have proved yourself to be a winner!
I hope you had some fun reading this article and you learned something useful!
Feel free to share this article with your friends and colleagues!