Python Comparison Operators

In the last lesson you learned Arithmetic Operators. There the result was a number. Now we look at a different kind of operator. These ones do not add or multiply. They ask a question about two values. Then they answer with a plain yes or no.

๐Ÿค” Why Do We Need Comparison Operators?

Think about almost any app you use. WhatsApp checks if your password is correct. Netflix checks if a person is old enough for a show. Uber checks if the driver is close enough to the rider.

Every one of those is a comparison. You take two values. You compare them. You get back a yes or no.

In Python, that yes or no has a name. It is called a boolean. A boolean has only two possible values: True or False. Comparison operators are the tools that give you one of those two answers. Once you have that answer, you can use it to make your program decide what to do next.

๐Ÿ” What Is a Comparison Operator?

A comparison operator takes two values. It compares them. Then it gives back True or False.

Here is a real-world way to picture it. Imagine Riya at the gate of a movie hall. The rule is โ€œyou must be 18 or olderโ€. She looks at one number, your age. She compares it to another number, 18. The answer is just yes or no. That is exactly what a comparison operator does.

Python gives you six of them. Here they are with a tiny example and the answer you get back.

Operator Means Example Result
== equal to 5 == 5 True
!= not equal to 5 != 3 True
> greater than 5 > 3 True
< less than 5 < 3 False
>= greater than or equal to 5 >= 5 True
<= less than or equal to 3 <= 5 True

๐Ÿ”ข Comparing Numbers

Let us start with numbers. That is the easiest place to see what is going on. This code compares a few numbers and prints each answer.

print(10 == 10)
print(10 != 7)
print(10 > 20)
print(10 < 20)
print(5 >= 5)
print(4 <= 2)

Each line asks a question. Python prints back True or False.

Output

True
True
False
True
True
False

Read them out loud and they make sense. Is 10 equal to 10? True. Is 10 greater than 20? False. The operator just answers the question.

๐Ÿ“ฆ The Answer Is a Value You Can Store

Here is something many people miss at the start. The result of a comparison is not just something to print. It is a real value, the same way a number is a real value. So you can save it in a variable and use it later.

This code works out whether someone is old enough to sign up, then keeps the answer in a variable.

age = 20
is_adult = age >= 18
print(is_adult)
print(type(is_adult))

Here is what each line does.

  • age = 20 stores the personโ€™s age in a variable.
  • age >= 18 compares that age to 18 and works out a True or False.
  • That answer gets saved in is_adult. So now is_adult holds True.
  • type(is_adult) shows what kind of value it is. It is a bool, short for boolean.

Output

True
<class 'bool'>

So remember this. A comparison gives back a value. You can print it, store it in a variable, or pass it into an if. We will use that idea in a minute.

๐Ÿ”ค Comparing Strings

Comparison operators are not only for numbers. You can compare strings too. This is how password checks and username checks work.

The most common one is ==. It asks โ€œare these two pieces of text exactly the same?โ€ This code checks a password.

correct_password = "open123"
entered_password = "open123"
print(entered_password == correct_password)

We compare the text the user typed with the real password. If every character matches, the answer is True.

Output

True

One thing to watch with strings. The comparison is case-sensitive. That means uppercase and lowercase letters are treated as different. So "Hello" and "hello" are not equal.

print("Hello" == "hello")
print("Hello" == "Hello")

The first line is False because the capital H does not match the small h. The second line matches exactly.

Output

False
True

๐Ÿ”  Strings Also Compare in Alphabetical Order

You can use < and > on strings too, not just ==. With text, Python compares in alphabetical order. So "apple" comes before "banana", which means "apple" < "banana" is True.

print("apple" < "banana")
print("cat" > "car")

Let me walk through it.

  • "apple" < "banana" checks โ€œdoes apple come before banana?โ€. The letter a comes before b, so yes. It is True.
  • "cat" > "car" compares letter by letter. c matches c, a matches a, then t comes after r. So "cat" is the bigger one. It is True.

Output

True
True

Now, why does this ordering work? Each character has a number behind it, called its Unicode code point. Python compares those numbers. And here is the catch most people trip on. All the uppercase letters have smaller numbers than the lowercase ones. So "Z" is actually less than "a".

print("Z" < "a")
print("Apple" < "apple")

So capital letters sort before small letters. "Apple" comes before "apple" because the capital A has a smaller code point than the small a.

Output

True
True

โš–๏ธ Comparing Different Types

What happens when the two values are not the same kind of thing? This is where you need to be a little careful, because == and < behave differently.

With ==, comparing across types is safe. Python just says โ€œthese are not the sameโ€, so you get False. The number 18 and the string "18" look alike to your eye, but to Python one is a number and the other is text.

print(18 == "18")
print(18 == 18)

Output

False
True

But < and > are stricter. Python does not know whether a number comes โ€œbeforeโ€ or โ€œafterโ€ a piece of text. So instead of guessing, it stops and raises an error. This is a TypeError.

print(18 < "18")

Output

Traceback (most recent call last):
File "main.py", line 1, in <module>
print(18 < "18")
TypeError: '<' not supported between instances of 'int' and 'str'

So keep this difference in mind.

  • == and != across different types are fine. You just get False or True, never an error.
  • <, >, <=, and >= across a number and a string crash with a TypeError.
  • The fix is simple. Convert the value first, so both sides are the same type. If a user types "18", turn it into a number with int("18") before you compare with <.

๐Ÿ”— Chained Comparisons

Here is a nice thing Python lets you do that reads just like school maths. Say you want to check that a number is between 0 and 10. You can write it in one line.

x = 7
print(0 < x < 10)

This says โ€œis x bigger than 0 AND smaller than 10?โ€. With x as 7, both parts are true, so the whole thing is True.

Output

True

What is really going on? Python reads 0 < x < 10 as two checks joined together. It is the same as writing 0 < x and x < 10. Both parts have to be true for the answer to be true.

This is great for range checks, like a score that must be between 0 and 100, or a temperature that should stay in a safe band. It reads the way you would say it out loud, so it is easy to get right.

๐ŸŒŠ One Calm Note About Comparing Floats

There is one place where == can surprise you, and it is good to know about it early. It happens with decimal numbers, the ones with a dot, called floats.

print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)

You would expect True, right? But you get False. The second print shows why.

Output

False
0.30000000000000004

Here is the plain-English reason. Computers store decimal numbers in binary, and some decimals like 0.1 cannot be stored exactly. So 0.1 + 0.2 comes out as a tiny bit more than 0.3. It is not a Python bug. Every language that stores floats this way has it.

So when you need to compare floats, do not use ==. Use math.isclose instead. It checks โ€œare these two numbers close enough?โ€, which is what you actually mean.

import math
print(math.isclose(0.1 + 0.2, 0.3))

Output

True

This only matters for floats. For whole numbers, == is exact and you have nothing to worry about.

๐Ÿšฆ Using Comparisons in if Statements

So far we have mostly been printing True and False. But the real reason these operators matter is that you can use the answer to make a decision. That is where if comes in.

An if statement runs some code only when a comparison is True. This example checks whether a person can watch a show.

age = 15
if age >= 18:
print("You can watch this show.")
else:
print("Sorry, this show is 18+.")

Walking through it.

  • age >= 18 is the comparison. With age 15, it gives False.
  • Because it is False, Python skips the if block and runs the else block.

Output

Sorry, this show is 18+.

You can chain a few comparisons together to grade something. This code turns a score into a letter grade.

score = 82
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Fail")

Python checks each comparison from top to bottom and stops at the first one that is True. A score of 82 is not 90 or more, but it is 75 or more, so it lands on Grade B.

Output

Grade B

And here is the password match you saw earlier, now actually deciding something.

correct_password = "open123"
entered = "open123"
if entered == correct_password:
print("Welcome back!")
else:
print("Wrong password.")

The == gives True, so the if block runs and the person is let in.

Output

Welcome back!

๐Ÿ” Using Comparisons in while Loops

Comparisons also drive while loops. A while loop keeps running as long as a comparison stays True. This countdown keeps going while the number is still above 0.

count = 3
while count > 0:
print(count)
count = count - 1
print("Go!")

Here is the flow.

  • count > 0 is checked before each turn of the loop.
  • While it is True, Python prints the number, then makes count one smaller.
  • When count reaches 0, the comparison becomes False, so the loop stops and we print โ€œGo!โ€.

Output

3
2
1
Go!

This is the heart of how programs make choices and repeat work. The comparison gives a True or False. The if or while uses that answer to pick what happens next.

โš ๏ธ Common Mistakes

The biggest trap here catches almost everyone when they start. So read this part slowly.

= and == look similar but do completely different jobs. One assigns a value. The other compares two values.

  • = (one equals sign) means โ€œput this value into this variableโ€. This is assignment.
  • == (two equals signs) means โ€œare these two values equal?โ€. This is comparison.

Here is the mistake and the fix side by side.

age = 18
# โŒ Avoid: one = sign tries to assign, not compare (this is a SyntaxError inside an if)
if age = 18:
print("adult")
# โœ… Good: two == signs compare the values
if age == 18:
print("adult")

If you run the wrong version, Python refuses to even start. It points at the spot and tells you the syntax is wrong.

Output

File "main.py", line 4
if age = 18:
^
SyntaxError: invalid syntax

A simple way to remember it. One equals sign gives. Two equals signs ask.

Another common slip is using < or > between a number and a string, expecting it to just work. As you saw above, == is fine there, but < raises a TypeError. Convert one side first.

user_input = "18"
# โŒ Avoid: comparing text to a number with < raises a TypeError
print(user_input > 10)
# โœ… Good: turn the text into a number first, then compare
print(int(user_input) > 10)

One more small thing. Watch the order of the symbols. It is >= and <=, with the equals sign second. Writing => or =< is wrong and Python will not accept it.

โœ… Best Practices

  • Read your comparison out loud as a question. If โ€œis age greater than or equal to 18?โ€ sounds right, the code is probably right.
  • Use == to compare and = only to assign. When something breaks in an if, check this first.
  • Give boolean variables a name that reads like a yes/no question, such as is_adult or has_paid. The code then almost explains itself.
  • For range checks, use chained comparisons like 0 < x < 100. They read like maths and are easy to get right.
  • Compare values of the same type. If you are comparing a typed-in value to a number, convert it with int() or float() first.
  • For decimal numbers, do not test equality with ==. Use math.isclose so tiny rounding differences do not bite you.

๐Ÿงฉ What Youโ€™ve Learned

  • โœ… Comparison operators compare two values and give back a boolean, which is either True or False.
  • โœ… The six operators are == (equal), != (not equal), >, <, >=, and <=.
  • โœ… The result is a real value, so you can store it in a variable and use it later.
  • โœ… == compares two values, while = assigns a value to a variable. They are not the same.
  • โœ… Strings compare in alphabetical order by Unicode code point, and the comparison is case-sensitive.
  • โœ… == across different types just gives False, but < between a number and a string raises a TypeError.
  • โœ… Chained comparisons like 0 < x < 10 mean 0 < x and x < 10.
  • โœ… For floats, avoid == and use math.isclose, because some decimals cannot be stored exactly.
  • โœ… The True or False result drives if statements and while loops, which is how programs decide and repeat.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does a comparison operator give back?

    Why: Comparison operators compare two values and return a boolean, either True or False.

  2. 2

    Which operator checks if two values are equal?

    Why: Two equals signs (==) compare two values, while a single = assigns a value to a variable.

  3. 3

    What is the result of 0 < 5 < 10 in Python?

    Why: Chained comparisons mean 0 < 5 and 5 < 10. Both parts are true, so the answer is True.

  4. 4

    Why is 0.1 + 0.2 == 0.3 False in Python?

    Why: Floats are stored in binary, and some decimals like 0.1 cannot be stored exactly, so the sum is a tiny bit off. Use math.isclose instead.

๐Ÿš€ Whatโ€™s Next?

You can now ask one question at a time and get a yes or no. Next you will learn how to combine several questions together, like โ€œis the password correct AND is the account active?โ€.

Logical Operators

Share & Connect