Python Not Equal

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.

Syntax

Following is the syntax of Python Not Equal comparison operator.

result = operand_1 != operand_2

where operand_1 and operand_2 are values of any datatype.

Not Equal operator returns a boolean value. The operator returns True if operand_1 and 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 !=.

Python Program

a = 10
b = 12
c = 12

print(a != b)
print(b != c)
Run this program

Output

True
False

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.

Python Program

a = 11

if a%2 != 0 :
    print(a, "is not even number.")
Run this program

Output

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.

Python Program

a = "python"
b = "javascript"

if a != b :
    print(a, 'and', b, 'are different.')
Run this program

Output

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.

Python Program

a = 4

while a != 0 :
    print("hello")
    a -= 1
Run this program

Output

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.

Python Program

a = 4
b = 5

if (a == 1) != (b == 5):
    print('Hello')
Run this program

(a == 1) and (b == 5) two simple conditions and we have use not equal operator to join them and form a compound condition.

Output

Hello

Summary

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.