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 hr
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
Certification available

Course

Intermediate Python

4 hr
1.1M
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.
See MoreRight Arrow
Related

podcast

The Venture Mindset with Ilya Strebulaev, Economist Professor at Stanford Graduate School of Business

Richie and Ilya explore the venture mindset, the importance of embracing unknowns, how VCs deal with unpredictability, how our education affects our decision-making ability, venture mindset principles and much more. 
Richie Cotton's photo

Richie Cotton

59 min

cheat sheet

LaTeX Cheat Sheet

Learn everything you need to know about LaTeX in this convenient cheat sheet!
Richie Cotton's photo

Richie Cotton

tutorial

Everything You Need to Know About Python Environment Variables

Learn the ins and outs of managing Python environment variables with os and python-dotenv libraries.
Bex Tuychiev's photo

Bex Tuychiev

9 min

tutorial

Everything You Need to Know About Python's Maximum Integer Value

Explore Python's maximum integer value, including system limits and the sys.maxsize attribute.
Amberle McKee's photo

Amberle McKee

5 min

tutorial

Python KeyError Exceptions and How to Fix Them

Learn key techniques such as exception handling and error prevention to handle the KeyError exception in Python effectively.
Javier Canales Luna's photo

Javier Canales Luna

6 min

tutorial

Troubleshooting The No module named 'sklearn' Error Message in Python

Learn how to quickly fix the ModuleNotFoundError: No module named 'sklearn' exception with our detailed, easy-to-follow online guide.
Amberle McKee's photo

Amberle McKee

5 min

See MoreSee More