Python NOT EQUAL operator
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.
Note: It is important to keep in mind that this comparison operator will return True if the values are same but are of different data types.
Syntax: Value A != Value B
Example 1: Comparing different values of the same data type
Python3
A = 1 B = 2 C = 2 print (A! = B) print (B! = C) |
Output:
True False
Example 2: Comparing same values of different data type
Python3
A = 1 B = 1.0 C = "1" print (A! = B) print (B! = C) print (A! = C) |
Output:
False True True
Example 3: Python not equal with custom object
The __ne__() gets called whenever the not equal operator is used. We can override this function to alter the nature of the not equal operator.
Python3
class Student: def __init__( self , name): self .student_name = name def __ne__( self , x): # return true for different types # of object if type (x) ! = type ( self ): return True # return True for different values if self .student_name ! = x.student_name: return True else : return False s1 = Student( "Shyam" ) s2 = Student( "Raju" ) s3 = Student( "babu rao" ) print (s1 ! = s2) print (s2 ! = s3) |
Output:
True True
Please Login to comment...