Comparison operations using the operator module

In this article we are going to use the operator module in python to compare two variables. The following comparisons are performed.

  1. Greater than
  2. Greater than or equal to
  3. less than
  4. less than or equal to
  5. equal

All these methods will return true or false based on the operation. This module can be use if you did not want to use the comparison operators.

1. Greater than

This method will get two numbers and return True if the first number is greater than the second number or returns False if the first number is lesser than the second number.

if a>b:
    return True
else:
    return False

greater than operator in python
greater than operator in python

2. less than

This method will get two numbers and return False if the first number is greater than the second number or returns True if the first number is lesser than the second number.

if a>b:
    return False
else:
    return True
lesser thann in python

3. lesser than or equal to

The lesser than or equal to operator will take two numbers and returns True if the first number is lesser than or equal to the second number, otherwise it will return False.

if a <= b:
    return True
else:
    return False
less than or equal to in python

4. greater than or equal to

The greater than or equal to operator will take two numbers and returns True if the first number is greater than or equal to the second number, otherwise it will return False.

if a >= b:
    return True
else:
    return False
greater than or equal to in python

5. equal

This method will take two numbers and return true if both the numbers are equal otherwise it will return false.

equal operator in python

Conclusion

This methods will be useful only if we do not wish to use the comparison operators. In one of the interviews i have attended they asked me to find the greatest of two numbers without using the comparison operators. I solved it in the following way.

num1 = 9
num2 = 5


if num1/num2 >= 1:
    print("num1 is greater")
else:
    print("num2 is greater")

I did not check for equal as they said that they both will not be equal. In this scenario we can use the operator module. It will have a good impression on the interviewers and will give them a good feeling about us that we know more modules and concepts from python.

Happy coding !