Python not equal operator With Example

Posted in /   /  

Python not equal operator With Example
vinaykhatri

Vinay Khatri
Last updated on May 30, 2024

    The "not equal to" operator is a comparison operator, and it returns a boolean value ( True or False) based on the comparison. The operator returns True if both the operands are of different data types or values, else it returns False. Python is a dynamic and strong typed language which mean it compares the variable data type as well its value when it comes to "equal to" and "not equal to" operators.

    Python not equal operator With Example

    In python 3 we represent the "not equal to" operator by != symbol.

    Example:

    >>> 20 != 30
    True
    
    >>> 20 != "20"
    True
    
    >>> 20 != 20
    False

    The != operator only operate between two operands or variables.

    Python "not equal to" custom object

    When we use the "not equal to" operator between two variables or objects, then at the backend the __ne__(self, other) method operates. This means we can use this Dunder method to create such user objects which could use python "not equal to" != operator.

    Example

    class Student:
        def __init__(self, name, lan):
            self.name= name
            self.lan = lan
    
        # Return True if two Student objects has different languages
        # If both student has same languages return False
        def __ne__(self,other):
            if self. lan != other.lan:
                return True
            else:
            return False
    
    rohit = Student("rohit", "Python")
    himanshu = Student("himanshu", "Java")
    raj = Student("raj", "Python")
    
    print("rohit != himanshu", rohit !=himanshu)
    print("rohit != raj", rohit!=raj)

    Output

    rohit != himanshu True
    rohit != raj False

    Summary

    • In python, the not equal operator is represented by != symbol.
    • The operator can operate between two objects or variables.
    • It returns True if both the variable has different values or data types.
    • It returns False if both the variables have similar values and data type.
    • For user-defined functions, it can be customise using __ne__() dunder.

    People are also reading:

    Leave a Comment on this Post

    0 Comments