Python logical operators

Python Comparison Operators are used to compare two objects. The output returned is a boolean value – True or False.

Python Comparison Operators

There are 6 types of comparison operators in Python.

Comparison Operator Description Example
== returns True if two operands are equal, otherwise False. a == b
!= returns True if two operands are not equal, otherwise False. a != b
> returns True if left operand is greater than the right operand, otherwise False. a > b
< returns True if left operand is smaller than the right operand, otherwise False. a < b
>= returns True if left operand is greater than or equal to the right operand, otherwise False. a > b
<= returns True if left operand is smaller than or equal to the right operand, otherwise False. a < b

Python Comparison Operators Example

Let’s look at a simple example of using comparison operators with primitive data type such as an integer.

Python Comparison Operators With Examples

Python Comparison Operator – Integer

Python Comparison Operators with String

The string is an object in Python programming. Let’s see whether comparison operators work with Strings or not.

Python Comparison Operators – String

Python Comparison Operators – String

So does it mean that comparison operators will work with any python objects?

Let’s check it out by creating a custom class.

Python Comparison Operator Overloading Error

Python Comparison Operator Overloading Error

Why equals and not-equals operator worked but others didn’t?

It’s because “object” is the base of every class in Python. And object provides an implementation of functions that are used for equals and not-equals operator.

Functions for Comparison Operators

Here is the list of functions that are used by comparison operators. So if you want comparison operators to work with the custom object, you need to provide an implementation for them.

Comparison Operator Function
== __eq__(self, other)
!= __ne__(self, other)
> __gt__(self, other)
< __lt__(self, other)
>= __ge__(self, other)
<= __le__(self, other)

Python Comparison Operators Overloading

Let’s look at an example to overload comparison operators in a custom object.

Output:

Summary

Python comparison operators are used to compare two objects. We can easily implement specific functions to provide support for these operators for our custom objects.

By admin

Leave a Reply

%d bloggers like this: