askvity

How to Check Not Equal To in Python?

Published in Python Operators 3 mins read

In Python, you check if two values are not equal using the != operator.

Understanding the Not Equal Operator (!=)

The != operator is a comparison operator used to determine if two values or variables are not equivalent. It's the opposite of the equality operator (==).

As stated in the reference, the does not equal sign in Python is !=. When you use this operator to compare two values:

  • If the values are indeed not equal to each other, the comparison evaluates to True.
  • If the values are equal to each other, the comparison evaluates to False.

The result of a != comparison is always a boolean value: either True or False.

How to Use the != Operator

Using the != operator is straightforward. You place it between the two values or expressions you want to compare.

value1 != value2

Here are some examples demonstrating its use with different data types:

  • Comparing Numbers:

    a = 10
    b = 20
    c = 10
    
    print(a != b) # Output: True (10 is not equal to 20)
    print(a != c) # Output: False (10 is equal to 10)
    print(5 != 5) # Output: False
    print(5 != 10) # Output: True
  • Comparing Strings:

    string1 = "hello"
    string2 = "world"
    string3 = "hello"
    
    print(string1 != string2) # Output: True ("hello" is not equal to "world")
    print(string1 != string3) # Output: False ("hello" is equal to "hello")
  • Comparing Different Data Types: Python can sometimes compare different types, but the result might be unexpected if types are incompatible. Generally, comparison works best between similar types.

    print(10 != "10") # Output: True (integer 10 is not equal to string "10")

Practical Examples

The != operator is commonly used in conditional statements, such as if and while loops, to control program flow based on whether a condition is met (the values are not equal).

Example in an if Statement

user_input = input("Enter 'quit' to exit: ")

if user_input != 'quit':
    print("You did not enter 'quit'. Program continues.")
else:
    print("You entered 'quit'. Program is exiting.")

Example in a while Loop

count = 0
while count != 5:
    print(f"Count is {count}")
    count += 1
print("Count reached 5.")

Summary of Comparison Operators

Here's a quick look at the main comparison operators in Python:

Operator Meaning Example Result (if a=5, b=10)
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b False
< Less than a < b True
>= Greater than or equal to a >= b False
<= Less than or equal to a <= b True

Using the != operator is the standard and most readable way to check for inequality in Python.

Related Articles