Asked 3 years ago
18 Sep 2021
Views 786
andy

andy posted

how to use not equal in Python ?

how to use not equal in Python ?
angeo

angeo
answered Sep 18 '21 00:00

suppose you have two variables x and y and you want to check they are not equal or not in Python.

x != y 

in above code, != (not equal) operator used to check both variable's value is not equal or not in Python.

!= (not equal) operator return boolean True or False in Python .
!= (not equal) operator return boolean False , if passed both variables's value are equal in Python.
!= (not equal) operator return boolean True , if passed both variables's value are not equal in Python.

!= (not equal) operator example in Python :

x=12
y=12
if(x!=y):
	print("x is not equal to y ")
else:
	print("x is equal to y ")


in the run of the above code, x!=y return False because x and y had the same value so it goes to else and Print : x is equal to y


!= (not equal) operator example in Python :

x=12
y=10
if(x!=y):
	print("x is not equal to y ")
else:
	print("x is equal to y ")


in the run of the above code, x!=y return boolean True because x and y are not equal so it going to Print : x is not equal to y
david

david
answered Sep 19 '21 00:00

Python has operator module.
operator module have also not equal to (ne()) method which had same funcationality as != (not equal) opeator.
!= and operator.ne() both work same .
you need to import operator module as below.

import operator


after importing the operator module, now use operator.ne(first value (or variable),second value( or variable))
operator.ne(a,b) returns True if both passed argument's value is not equal or False if both passed argument's value is equal,


x=102
y=102
if(operator.ne(x,y))
         # do code here for a and b are not equal

in above code operator.ne(x,y) return False


x="102"
y=102
if(operator.ne(x,y))
         # do code here for a and b are not equal

in the above code operator.ne(x,y) return True. because Python is a Strongly Typed programming language. and x have string type value and y have integer value so there not equal in type so it returns False

operator.ne() is check value and type both
ajamil

ajamil
answered Sep 19 '21 00:00

"is not " can also be used for the checking not equal in Python.
"is not " operator is equal to "!=" not equal comparison operator.


a=1
b=1
print(a is not b)

Output : False
because 1 and 1 both are equal

now lets use dynamic value or object

str1='hiw'
str2='hi'
print(str1 is not str2)

Output : True
in above code is not return True because both string is not same


Post Answer