Booleans

Introduction to Comparison Operators

Learn how to compare different values with each other and understand how Booleans indicate the result of these comparisons.


A common application of Booleans is in the context of comparisons. In programming, we frequently want to compare different values with each other to make decisions about the flow of our programs.

For example, sometimes you might want to determine whether two values are the same or different. You can do so using the Equal operator (==).

Here, we have two variables with numbers. We use the Equal operator (==) to compare these:

num1 = 2 num2 = 3 # check if num1 and num2 are equal: print(num1 == num2)
Python
Output

As you can see, the result of this comparison is a Boolean. False indicates that num1 and num2 are not equal.

We can also directly compare two values without relying on variables:

print(2 == 2)
Python
Output

Comparing values also works with strings:

# Note that the comparison is case sensitive: print('paris' == 'PARIS') print('Paris' == 'Paris')
Python
Output

It even works with Booleans:

print(True == False)
Python
Output

But checking for equality is not the only comparison between values we can do. Let's see what other Comparison Operators there are:

The Not Equal operator (!=) checks if two values are not equal.

2 != 2
Python

Can you guess the output?

print(2 != 3) print(2 != 2)
Python
Output

The Greater Than operator (>) checks if the value on the left is greater than the value on the right. For instance:

# is 2 greater than 1? print(2 > 1)
Python
Output

The Less Than operator (<) checks if the value on the left is less than the value on the right. For instance:

# is 2 less than 1? print(2 < 1)
Python
Output

Similar to the operators above, there are also the Less Than or Equal (<=) and the Greater Than or Equal (>=) operators.

2 <= 1 # Checks if 2 is less than or equal to 1 2 >= 1 # Checks if 2 is greater than or equal to 1
Python

Let's see the difference between <= and <:

# is 2 less than 2? print(2 < 2) # is 2 less than or equal 2? print(2 <= 2)
Python
Output

What will be the output?

print(2 == '2')
Python

What will be the output?

print(False == False)
Python

What will be the output?

print(100 != 100)
Python

What will be the output?

print(100 != 200)
Python

What will be the output?

print(100 < 200)
Python

What will be the output?

print(100 >= 100)
Python

What will be the output?

print(100 > 100)
Python

Last but not least, you can even chain multiple Comparison Operators together and combine them with other expressions.

Here, we check if the sum of two numbers falls within the range of 0 to 10:

# is the sum of 2 and 5 in range? print(0 < 2 + 5 < 10)
Python
Output

What will be the output?

print(100 < 200 < 200)
Python

What will be the output?

print(100 <= 200 <= 200)
Python

What will be the output?

print(100 >= 50 + 51)
Python