Python Not Equal – Comparison Operator
Python Not Equal is a Comparison Operator used to check if two values are not equal.
The symbol used for Python Not Equal operator is
!=. There should be no separator between exclamatory symbol and equal symbol.
! is referred to as not.
Not Equal Operator is mostly used in boolean expressions of conditional statements like If, If-Else, Elif, While, etc.
Following is the syntax of Python Not Equal comparison operator.
result = operand_1 != operand_2
operand_2 are values of any datatype.
Not Equal operator returns a boolean value. The operator returns True if
operand_2 are not equal values, else it returns False.
Example 1: Not Equal Comparison Operator
In this example, we shall take two integers, and check if they are not equal using
a = 10 b = 12 c = 12 print(a != b) print(b != c)
a and b are not equal and therefore
a != b returned True.
a and c are equal and therefore
a != b returned False.
Example 2: Not Equal Operator with IF Statement
We already know that not equal operator returns a boolean value. Therefore, this can be used in conditions of decision making statements.
In the following example, we shall use not equal operator in IF statement condition.
a = 11 if a%2 != 0 : print(a, "is not even number.")
11 is not even number.
a%2 != 0 returns True for
a=11. And therefore, if block is executed.
Example 3: Not Equal Operator with Strings
In this example, we shall use Not Equal operator to check if two strings are not equal.
a and b have same value.
Clearly, the two strings are not equal and the result of
a != b is True. So, Python executes the if block code.
Example 4: Not Equal Operator in While Condition
You can use not equal operator in while loop condition.
a = 4 while a != 0 : print("hello") a -= 1
hello hello hello hello
Example 5: Not Equal Operator in Compound Condition
not equal operator can be used to combine simple conditions and form compound conditions or boolean expressions.
a = 4 b = 5 if (a == 1) != (b == 5): print('Hello')
(a == 1) and
(b == 5) two simple conditions and we have use not equal operator to join them and form a compound condition.
In this tutorial of Python Examples, we learned what Python Not Equal Comparison Operator is, how to use it to find if two values are not equal, with the help of well detailed example programs.