Python Comparison and Logic
Learn Python comparison and logic: ==, !=, <, >, the True and False booleans, and the and, or, not operators. Build conditions for if statements with runnable code, a worked example and a quiz.
Key takeaways
- Comparisons like ==, !=, <, > and >= produce a boolean: either True or False
- Use == to compare two values, but use a single = to assign a value to a variable
- and is True only when both sides are True; or is True when at least one side is True
- not flips a boolean, turning True into False and False into True
- Boolean expressions are the conditions that power if statements
Asking the computer questions
Programs constantly need to make decisions. Is the player out of lives? Is the password correct? Is the temperature too high? Before a program can decide anything, it has to ask a question and get a yes-or-no answer. In Python those answers are called booleans, and the questions are built from comparison and logic operators.
This is the engine behind the conditionals in Python you may have already seen with if. Here we'll look closely at how the conditions themselves work.
True and False: the booleans
A boolean is a value that is either True or False. Those two words are special in Python and must always start with a capital letter.
is_raining = True
is_sunny = False
print(is_raining) # True
print(type(is_raining)) # <class 'bool'>
is_raining = Truestores the booleanTruein a variable.type(is_raining)confirms its type isbool, short for boolean.
Booleans are the simplest type in Python — only two possible values — but they're the foundation of every decision your program makes.
Comparison operators
A comparison checks how two values relate, and the result is always a boolean. Here are the six comparisons:
print(5 == 5) # True equal to
print(5 != 3) # True not equal to
print(5 > 3) # True greater than
print(5 < 3) # False less than
print(5 >= 5) # True greater than or equal to
print(3 <= 2) # False less than or equal to
Reading these:
==asks "are these equal?" —5 == 5isTrue.!=asks "are these different?" —5 != 3isTruebecause they are.>,<,>=and<=compare sizes, just like in maths.
The most important point: == is a question, = is a command. A single = stores a value (x = 5), while a double == checks equality (x == 5). Mixing them up is the classic beginner bug.
Comparisons work on text too, checking whether strings match exactly:
password = "open123"
print(password == "open123") # True
print(password == "Open123") # False (capital O is different)
String comparison is case-sensitive, so "open123" and "Open123" are not equal.
Combining conditions with and, or, not
Often a single comparison isn't enough. You might need two things to be true at once, or either of two things. Python gives you three logical operators: and, or, and not.
and is True only when both sides are True:
age = 15
print(age > 12 and age < 18) # True
print(age > 12 and age < 14) # False
age > 12isTrueandage < 18isTrue, so the whole thing isTrue.- In the second line,
age < 14isFalse, and becauseandneeds both sides, the result isFalse.
or is True when at least one side is True:
day = "Saturday"
print(day == "Saturday" or day == "Sunday") # True
print(day == "Monday" or day == "Sunday") # False
- The first line is
Truebecause the left side matches. - The second line is
Falsebecause neither side isTrue.
not flips a boolean to its opposite:
print(not True) # False
print(not (5 > 3)) # False, because 5 > 3 is True
print(not (5 < 3)) # True, because 5 < 3 is False
A simple way to remember it: and is strict (everything must be true), or is generous (one is enough), and not is the opposite-switch.
Putting it inside an if statement
These boolean expressions are exactly what if statements check:
temperature = 30
if temperature > 25 and temperature < 35:
print("Warm but comfortable")
else:
print("Outside the comfort zone")
- The condition
temperature > 25 and temperature < 35becomesTrue, so the first branch runs and printsWarm but comfortable. - If the temperature were
40, the condition would beFalseand theelsebranch would run instead.
Worked example: a login check
Let's build a small login checker that requires the right username and the right password.
correct_user = "ada"
correct_pass = "lovelace"
username = "ada"
password = "lovelace"
logged_in = (username == correct_user) and (password == correct_pass)
if logged_in:
print("Welcome, " + username + "!")
else:
print("Login failed.")
How it works:
username == correct_userchecks the name and produces a boolean.password == correct_passchecks the password and produces another.- The
andcombines them:logged_inis onlyTrueif both match. If either is wrong,logged_inisFalse. - The
if logged_in:line then uses that boolean to decide which message to print.
Try changing the password to "wrong". Now the second comparison is False, the and makes logged_in False, and the program prints Login failed. — exactly the safe behaviour you'd want.
Try it yourself
Write a program that decides whether someone can ride a rollercoaster. The rule is: you must be at least 12 years old AND at least 140 cm tall.
- Create two variables,
ageandheight. - Build one boolean:
can_ride = age >= 12 and height >= 140. - Use an
ifto print either"You can ride!"or"Sorry, not yet.".
Then test it with different values: a tall 10-year-old, a short 14-year-old, and a 13-year-old who is 145 cm. Only the last one should pass. When you're confident, revisit conditionals in Python to combine these conditions with elif for even smarter decisions.
Quick quiz
Test yourself and earn XP
What does 5 > 3 evaluate to?
5 is greater than 3, so the comparison is True.
What is the difference between = and ==?
A single = stores a value in a variable. A double == asks a question: are these two values equal?
What does (5 > 3) and (2 > 7) give?
and needs both sides to be True. 5 > 3 is True but 2 > 7 is False, so the whole thing is False.
What does not (3 == 3) give?
3 == 3 is True, and not flips it, so the answer is False.
When is an or expression True?
or is True if either the left side, the right side, or both are True. It is only False when both sides are False.
FAQ
The single = already has a job: it assigns a value to a variable, like x = 5. If = also meant 'is equal to', Python could not tell whether you wanted to store a value or test it. So Python uses == purely for the question 'are these equal?'. Mixing them up is one of the most common beginner mistakes, and Python will usually give you an error if you use = where a comparison is needed.
A boolean is the simplest data type in Python: it can only be one of two values, True or False (always capitalised). Every comparison produces a boolean, and booleans are what if statements check to decide which branch of code to run. You can also store a boolean in a variable, like is_open = True, and use it later.
Keep exploring
More in Coding