πPython Not Equal Operator (!=)
Python Not Equal Operator : The Python Not Equal Operator (!=) is used to compare two values and returns True if the values are different; otherwise, it returns False. Python’s flexibility and dynamic nature make it a powerful language for handling various data types and conditions using this operator.
πTypes of Not Equal Operators in Python
Python Not Equal Operator
Python supports two types of Not Equal operators:
- != β Used in Python 2 and Python 3.
- <> β Used only in Python 2 (deprecated in Python 3).
πSyntax
- X != Y β Recommended syntax for Python 3.
- X <> Y β Outdated syntax for Python 2.
πExamples of Python Not Equal Operator
πExample 1: Same Data Type but Different Values
python
A = 44
B = 284
C = 284
print(B != A) # Output: True
print(B != C) # Output: False
πExample 2: Different Data Types but Same Values
python
C = 12222
X = 12222.0
Y = “12222”
print(C != X) # Output: False
print(X != Y) # Output: True
print(C != Y) # Output: True
πUsing Not Equal Operator with if Statement
The if statement can check conditions using the != operator.
πExample:
python
X = 5
Y = 5
if X != Y:
print(“X is not equal to Y”)
else:
print(“X is equal to Y”)
Output: X is equal to Y
πUsing == Operator with while Loop
The == operator can be combined with a while loop to iterate as long as a condition is true.
πExample:
python
m = 300
while m <= 305:
m += 1
if m % 2 == 0:
continue
print(m)
πOutput:
301
303
305
πUsing Not Equal Operator with while Loop
The != operator can also be combined with a while loop to filter certain conditions.
πExample:
python
m = 300
while m <= 305:
m += 1
if m % 2 != 0:
continue
print(m)
πOutput:
302
304
306
πUsing Not Equal Operator with Custom Objects
Python allows developers to define custom conditions using the __ne__ method.
πExample:
python
class G9Example:
s_n = ”
def __init__(self, name):
self.s_n = name
def __ne__(self, x):
if type(x) != type(self):
return True
if self.s_n != x.s_n:
return True
else:
return False
G1 = G9Example(“Software Moji Moji”)
G2 = G9Example(“HipHop Moji”)
G3 = G9Example(“Software Moji Moji”)
print(G1 != G2) # Output: True
print(G2 != G3) # Output: True
print(G1 != G3) # Output: False
πComparison Operators in Python
Operator | Description | Example |
!= | Not equal to | A != B |
== | Equal to | A == B |
>= | Greater than or equal to | A >= B |
<= | Less than or equal to | A <= B |
> | Greater than | A > B |
< | Less than | A < B |
πUseful Tips for Using Not Equal Operator
β
Use != for better compatibility in Python 3.
β
Avoid <> as it is deprecated in Python 3.
β
In formatted strings, ensure you use != and not β , which may appear in certain fonts or editors.
β
The != operator is powerful for filtering data conditions, especially in dynamic data types.