Python Comparison Operators
Table of Contents + โ
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
TrueTrueFalseTrueTrueFalseRead 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 = 20is_adult = age >= 18print(is_adult)print(type(is_adult))Here is what each line does.
age = 20stores the personโs age in a variable.age >= 18compares that age to 18 and works out aTrueorFalse.- That answer gets saved in
is_adult. So nowis_adultholdsTrue. type(is_adult)shows what kind of value it is. It is abool, 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
TrueOne 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
FalseTrue๐ 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 letteracomes beforeb, so yes. It isTrue."cat" > "car"compares letter by letter.cmatchesc,amatchesa, thentcomes afterr. So"cat"is the bigger one. It isTrue.
Output
TrueTrueNow, 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
TrueTrueโ๏ธ 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
FalseTrueBut < 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 getFalseorTrue, 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 withint("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 = 7print(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
TrueWhat 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
False0.30000000000000004Here 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
TrueThis 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 >= 18is the comparison. With age 15, it givesFalse.- Because it is
False, Python skips theifblock and runs theelseblock.
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 BAnd 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 > 0is checked before each turn of the loop.- While it is
True, Python prints the number, then makescountone smaller. - When
countreaches 0, the comparison becomesFalse, so the loop stops and we print โGo!โ.
Output
321Go!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 valuesif 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 syntaxA 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 TypeErrorprint(user_input > 10)
# โ
Good: turn the text into a number first, then compareprint(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 anif, check this first. - Give boolean variables a name that reads like a yes/no question, such as
is_adultorhas_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()orfloat()first. - For decimal numbers, do not test equality with
==. Usemath.iscloseso tiny rounding differences do not bite you.
๐งฉ What Youโve Learned
- โ
Comparison operators compare two values and give back a
boolean, which is eitherTrueorFalse. - โ
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 givesFalse, but<between a number and a string raises a TypeError. - โ
Chained comparisons like
0 < x < 10mean0 < x and x < 10. - โ
For floats, avoid
==and usemath.isclose, because some decimals cannot be stored exactly. - โ
The
TrueorFalseresult drivesifstatements andwhileloops, which is how programs decide and repeat.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does a comparison operator give back?
Why: Comparison operators compare two values and return a boolean, either True or False.
- 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
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
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?โ.