Skip to main content
HomeTutorialsPython

Exploring the Python 'Not Equal' Operator

Comparing values in Python to check if they are not equal is simple with the not equal operator. Check out this quick tutorial on how to use the not equal Python operator, as well as alternatives for comparing floats.
Feb 2024  · 5 min read

Operators in Python allow us to perform various operations on data. They play a crucial role in programming, allowing Python developers to manipulate and compare values. One important relational operator in Python is the 'Not Equal' operator (!=). In this tutorial, we'll delve into the significance of this operator, its syntax, practical applications, and some common issues.

Understanding Operators and Operands

Before we delve into the 'Not Equal' operator, let's briefly explore the concepts of operators and operands. Operators are symbols that perform operations on one or more operands.

For instance, in the expression 2 + 3, the + is the operator, and 2 and 3 are operands. Operators can include arithmetic operators like addition and multiplication, as well as relational operators like 'Not Equal.' You can learn more in this Python operators tutorial.

The 'Not Equal' Operator in Python

The 'Not Equal' operator (!=) is a relational operator that compares two values for inequality. Below is an example of the syntax:

value1 != value2

If value1 is not equal to value2, the expression returns True; otherwise, it returns False. Let's explore this with numeric and non-numeric data types.

When comparing numeric values, the != operator simply compares whether the two numbers are the same or not.

num1 = 10
num2 = 20
result = num1 != num2
print(result)
Output: True

In this example, the 'Not Equal' operator compares num1 and num2, and since they are not the same, the result is True.

Similarly, the 'Not Equal' operator can be used with non-numeric data types like strings:

str1 = "hello"
str2 = "world"
result = str1 != str2
print(result)
Output: True

Here, str1 and str2 are not the same string, resulting in True. Be cautious, however. Capitalization counts with this method, meaning “Hello” will be considered to not be equal to “hello.”

Key takeaway: The != operator is the standard method for checking inequality.

Combining logic with conditional statements

The 'Not Equal' operator can be used in conjunction with conditional statements, such as if statements, to make decisions. If you are not familiar with conditional statements in Python, I recommend checking out this conditionals tutorial.

In the example below, we compare whether a person is the same age as they were previously to determine whether or not to wish them a happy birthday.

previous_age = 25
current_age = 26

# Checking if the current age is not equal to the previous age
if current_age != previous_age:
	print("Happy Birthday!")

You can also combine != with other logical operators for more complex scenarios. The example below could be used as part of a script to give more detailed information about a student’s progress in a course.

score = 85
if score >= 70 and score != 100:
print("The student passed but did not get a perfect score.")

Key takeaway: the != operator can be paired with conditional statements to make decisions efficiently.

Precision Comparisons with math.isclose()

Sometimes, particularly when dealing with floats, determining precise equality can be challenging due to the nature of floating-point representation. The math module in Python provides the isclose() function for more robust equality checks.

import math
value1 = 0.1 + 0.2
value2 = 0.3
if math.isclose(value1, value2): print("The values are approximately equal.")
else: print("The values are not equal.")
Output: The values are approximately equal.

Essentially, this comparison is checking whether the two floats are close enough that they can be considered to be equal.

Key takeaway: when comparing floats, math.isclose() is a better method for checking inequality than the != operator.

Troubleshooting Common Issues

Type errors are the most frequent errors when using the ‘Not Equal’ operator. This results from using != with incompatible data types. You can always use a type conversion method to ensure your comparisons are using the same data type. In the example below, because we are comparing an integer with a string, we get the wrong answer from our query.

num = 5
text = "5"
result = num != text

print(result)
Output: True

Another common problem when using operators is creating accidental logical fallacies, which can cause unexpected results. Ensure your conditional logic aligns with the intended comparisons, including in edge cases, to avoid errors in your code. Testing your code is essential for finding inadvertent logical fallacies, as not all of them will be flagged by the Python system as errors. Brush up on logical concepts with the intermediate Python course on DataCamp.

Conclusion

The Python 'Not Equal' operator is a powerful tool for comparing values and making decisions based on the result. Whether used in basic numeric comparisons or in conditional statements, the ‘Not Equal’ operator is a useful addition to your programming toolkit. Learn more about operators in DataCamp’s Python programming skill track.


Photo of Amberle McKee
Author
Amberle McKee

I am a PhD with 13 years of experience working with data in a biological research environment. I create software in several programming languages including Python, MATLAB, and R. I am passionate about sharing my love of learning with the world.

Topics

Keep Learning Python!

track

Python Fundamentals

15hrs hours
Grow your programmer skills. Discover how to manipulate dictionaries and DataFrames, visualize real-world data, and write your own Python functions.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

SQL NOT EQUAL Operator: A Beginner's Guide

Unlock the power of SQL NOT EQUAL with our expert guide. Learn to refine data queries with practical examples and optimization tips for better analysis.
Abid Ali Awan's photo

Abid Ali Awan

5 min

tutorial

Python Logical Operators: A Hands-on Introduction

Python offers three logical operators: and, or, and not. These operators, also known as Boolean operators, evaluate multiple conditions and determine an expression's overall truth value.
Stephen Gruppetta's photo

Stephen Gruppetta

17 min

tutorial

Operators in Python

This tutorial covers the different types of operators in Python, operator overloading, precedence and associativity.
Théo Vanderheyden's photo

Théo Vanderheyden

9 min

tutorial

SQL NOT IN Operator: A Comprehensive Guide for Beginners

Master SQL's NOT IN operator with this beginner's guide. Learn to filter data effectively, avoid common pitfalls, and explore efficient alternatives
Abid Ali Awan's photo

Abid Ali Awan

5 min

tutorial

Python IF, ELIF, and ELSE Statements

In this tutorial, you will learn exclusively about Python if else statements.
Sejal Jaiswal's photo

Sejal Jaiswal

9 min

tutorial

Python NaN: 4 Ways to Check for Missing Values in Python

Explore 4 ways to detect NaN values in Python, using NumPy and Pandas. Learn key differences between NaN and None to clean and analyze data efficiently.
Adel Nehme's photo

Adel Nehme

5 min

See MoreSee More