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.
Updated 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

Becoming Remarkable with Guy Kawasaki, Author and Chief Evangelist at Canva

Richie and Guy explore the concept of being remarkable, growth, grit and grace, the importance of experiential learning, imposter syndrome, finding your passion, how to network and find remarkable people, measuring success through benevolent impact and much more. 
Richie Cotton's photo

Richie Cotton

55 min

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

Seaborn Heatmaps: A Guide to Data Visualization

Learn how to create eye-catching Seaborn heatmaps
Joleen Bothma's photo

Joleen Bothma

9 min

Test-Driven Development in Python: A Beginner's Guide

Dive into test-driven development (TDD) with our comprehensive Python tutorial. Learn how to write robust tests before coding with practical examples.
Amina Edmunds's photo

Amina Edmunds

7 min

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

See MoreSee More