×

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as the name suggests, these operators are used to compare the values of two operands. These are the same operators we use in mathematics:

  1. Greater than - >
  2. Less than - <
  3. Greater than or equal to - >=
  4. Less than or equal to - <=
  5. Equals - ==

The one new operator is the "not equal to" operator. It is the opposite of equal to operator. How interesting is that? This article discusses the "not equal to" operator with examples.

Operator: ! =

Name: Not equal to

Type: Comparison operator

Syntax: value 1! = value 2

Return Type: Boolean

Return value:  If value1 and value2 on either side of the operator are not equal, True will be returned; else, False will be returned if both the values are equal.

Example programs:

1:

a = int (input ("Enter the first number: "))
b = int (input ("Enter a number to compare: "))
print (a != b)

Output:

Case 1:

Enter the first number: 3

Enter a number to compare: 3

False

Case 2:

Enter the first number: 4

Enter a number to compare: 8

True

Understanding:

The program takes input for two numbers to use the operator. If the user gives the same input for both the numbers, the operator returns False, and when different inputs are given, it returns true.

#2:

As a condition:

a = int (input ("Enter the first number: "))
b = int (input ("Enter a number to compare: "))
res = a != b
if (res == True):
    print ("The values are not equal")
else:
    print ("The values are not equal")

Output:

Case 1:

Enter the first number: 3

Enter a number to compare: 2

The values are not equal

Case 2:

Enter the first number: 3

Enter a number to compare: 3

The values are equal

Understanding:

In the above program, we compared two numbers, stored the result in res, and used it as a condition in the if statement to print if the two values are equal.

#3 Data type variation

a = int (input ("Enter the first number: "))
b = input ("Enter a number to compare: ")
res = a != b
if (res == True):
    print ("The values are not equal")
else:
    print ("The values are not equal")

Output:

Case 1:

Enter the first number: 4

Enter a number to compare: 4

The values are not equal

Understanding:

The input is the same for both values. But why is it false? It is because, when taking the input for the second number, int is not mentioned. Hence, the first number is an integer, and the second number is a string. An integer is not equal to a string.

  • Even if we take the same number, if both the numbers are of different data types, they are not considered equal.
  • If multiple comparison operators are used, there is no proper rule for precedence and associativity. Unless the expression is well-defined with parenthesis, it is evaluated from left to right by breaking it down into pieces.

If we say 2! = 3! = 4

We get true: It compares if the three values are equal.

But if we say:

X < Y < Z

This expression neither means (X < Y) < Z nor X < (Y < Z). It just means X < Y and Y < Z. By default, it will be evaluated from left to right.

Examples:

#Operator overloading
class not_eq :
    def __init__ (self, num):
        self. num = num
    def __ne__ (self, a):
        if (type (a. num) != type (self. num)):
            return True
        if self. num != a. num:
            return True
        else:
            return False
obj1 = not_eq (int (input ("Enter number 1: ")))
obj2 = not_eq (int (input ("Enter number 2: ")))
print (obj1 != obj2)

Output:

Enter number 1: 3

Enter number 2: 2

True

Understanding:

In the program, we created a class, “not_eq," in which we wrote our magic method __ne__ () -> the predefined function that gets invoked by default when we call the! = operator anywhere in the program. We created two objects with values taking inputs from the user and used the! = operator. By overloading the operator, we can now compare two objects.


Related Topics

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python MySQL Client

MySQL client is a project that is the subdivision of the MySQLdb package. This package provides an interface that runs the Python database API. Installing mysqlclient You can easily install mysqlclient with...

5 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 minutes read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.