...

/

Comparison Operators

Comparison Operators

Get familiar with comparisons in Python using comparison operators, including basic comparisons, as well as the 'is' and 'is not' operators.

Comparison operators can be used to compare values in mathematical terms. The precedence of comparison operator is same.

Symbol

Operator

>

Greater Than

<

Less Than

>=

Greater Than or Equal To

<=

Less Than or Equal To

==

Equal To

!=

Not Equal To

Output of comparison operators

The result of a comparison is always a bool. If the comparison is correct, the value of the bool will be True. Otherwise, its value will be False.

Try it yourself

Let’s look at a few examples. Our AI Mentor can explain the code as well.

Press + to interact
num1 = 5
num2 = 10
num3 = 10
print(num2 > num1)
print(num1 > num2)
print(num2 == num3)
print(num3 != num1)
print(3 + 10 == 5 + 5)
print(3 <= 2)

Identity operators

In Python, the is and is not operators are used to compare the memory locations of two objects. They help determine if two variables reference the same object in memory. Here’s an example demonstrating how is and is not operators are used and how they differ from the equality operator.

Press + to interact
original_list = [1, 2, 3]
same_reference_list = original_list
different_list = [1, 2, 3]
reordered_list = [1, 3, 2]
print(original_list is same_reference_list)
print(original_list is different_list)
print(original_list == different_list)
print(original_list == reordered_list)
# Example with integers
first_number = 10
second_number = 20
third_number = 10
print(first_number is not second_number)
print(first_number is not 10)
same_reference_number = first_number
print(same_reference_number is first_number)

Explanation

...