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
Operator | Usage | Example | Meaning |
< | to see if 1st object is less than the 2nd object | x < y | is x less than y? |
<= | to see if 1st object is less than or equal to the 2nd object | x <= y | is x either less than y or equal to y? |
What is < in python?
The ‘<‘ operator, pronounced as “less than”, is used to compare 2 objects and returns True if the 1st object is less than the 2nd object, returns False otherwise.
What is <= in python?
The ‘<=’ operator, pronounced as “less than or equal to”, is used to compare 2 objects and returns True if the 1st object is less than the 2nd object or if the 1st object is equal to the 2nd object, returns False otherwise.
In other words, the “<=” operator returns False if the 1st object is greater than the 2nd object, returns True otherwise.
An example is worth 1000 words, so here is one for you!
>>> 2 < 1
False
>>> 2 <= 2
True
>>> 3 <= 2
False
In this simple session at the Python interpreter
- 1st line says “is 2 less than 1”, which returns False as expected
- 3rd line says “is 2 less than or equal to 2”, which returns True because even though 2 is not less than 2, 2 is equal to 2!
- 5th line says “is 3 less than or equal to 2”, which returns False because 3 is neither less than nor equal to 2!
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 “lesser than” another?
Read on! I promise you will learn a thing or 2 as we have merely scratched the surface on the powers you can wield with these operators!
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 “less than” (<) and “less 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
>>> 2 < 1
False
>>> 2 <= 2
True
>>> 3 <= 2
False
So basically
- if there is any expression in the form “x< y” we get True if x is less than y and
- if there is any expression in the form “x<= y” we get True if x is less than y or if x is equal to y
Now let us look at a more complicated example with strings!
>>> 'cat' < 'elephant'
True
>>> 'dog' <= 'bear'
False
A 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 lesser than the other.
Let us take a look at another simple example of comparing 2 strings.
>>> str1 = "apple"
>>> str2 = "banana"
>>> str2 < str1
False
>>> str2 = "apple"
>>> str2 <= str1
True
Here
- 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 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 “less than” (<) and “less 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 really need to waste less time on FB and code more!")
else:
print("You have a going to be a great programmer very soon!")
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
- then we make a comparison of these 2 values and give some suggestion to the user!
Running a 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 less 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("These are the numbers from 1 to 5!")
num = 1
while (num <= 5)
print(num)
num = num + 1
This prints
These are the numbers from 1 to 5!
1
2
3
4
5
You might be thinking why not use the “<” operator and write the same program like this!
print("These are the numbers from 1 to 5!")
num = 1
while (num < 6)
print(num)
num = num + 1
This will give the same exact output
These are the numbers from 1 to 5!
1
2
3
4
5
Then
Why use “<=” when we have “<“?
The answer is READABILITY!
We wish to print 1 to 5, 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 6 just makes things unnecessarily complicated to read and figure out!
To give you another example
age_string = input("Please enter your age: ")
age_integer = int(age_string)
if age_integer < 18:
print("You cannot vote in the upcoming elections")
else:
print("Hope you make a good choice for 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 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 “less than” (<) and “less 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!
To get there first we must understand how these operators are implemented in Python.
How ‘<=’ 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.
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.
>>> help(str)
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 lt() and another one named le() as shown in the screenshots below.
These methods are available in all inbuilt classes like str, int, etc,.
Let us try to understand what these methods do for integers!
>>> a = 20
>>> b = 30
>>> a.__lt__(b)
True
>>> a.__le__(b)
False
>>> b = 20
>>> a.__le__(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.
- lt stands for ‘less than’ and
- le stands for ‘less 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!
so
a < b Becomes a.lt(b)
and
a <= b Becomes a.le(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, and you have your own logic of comparing 2 objects of the class you defined yourself. Then if you want the “<” and “<=” operators to work on your class, you need to implement the lt() and le() methods in your own class.
Let us see how to do that 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'
Here we have made 2 objects: apple and mango,
- with apple being priced at 10 bucks per kg and
- the mango 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!
Next, let us see how to solve this problem!
How to implement ‘<‘ 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 lt() and le() methods as shown below.
class fruit():
def __init__(self, name, price_kg):
self.name = name
self.price_kg = price_kg
def __lt__(self, b):
return (self.price_kg < b.price_kg)
def __le__(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()
- lt() and
- le() 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)
>>> peach < kiwi
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 the “<” and “<=” operators in Python!
Related Operators
There are some more operators in python which act very similar to less 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:
- > : Greater than
- >= : Greater than or Equal to
- == : Equal to
- != : Not Equal to
All these operators are implemented and used very similar to the way we use the “==” operator.
We have written a separate article explaining each of them using examples, please check them out in the link below!
Python Comparison Operators Explained Using 10 Examples!
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 related articles section below.
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!