Booleans and comparisons¶
~15 min ยท prerequisite: Reading error messages
What you will be able to do¶
- Write comparisons with
==,!=,<,<=,>, and>=, and predict whether each one givesTrueorFalse. - Combine two conditions with
and,or, andnot. - Spot the mistakes that make a comparison fail with an error, or pass when it should not.
The idea¶
A comparison asks a question about two values. The answer is always a boolean, which is True or False. The expression 3 < 5 asks "is 3 less than 5?" and gives True. The expression 3 > 5 gives False.
The six comparison operators are:
==checks that two values are equal.!=checks that two values are not equal.<and>check less than and greater than.<=and>=check less than or equal to, and greater than or equal to.
Remember the difference between = and ==. As you saw in Variables and types, = stores a value and == compares two values.
A condition is any expression that gives True or False. The next two lessons use conditions to decide what a program does and how often it repeats.
You can combine booleans with three words. Python calls them logical operators:
andgivesTrueonly when both sides areTrue.orgivesTruewhen at least one side isTrue.notturnsTrueintoFalse, andFalseintoTrue.
Python evaluates and and or from left to right and stops as soon as the result is known. This is called short-circuit evaluation. If the left side of and is False, the whole expression is False, so Python never evaluates the right side. This matters when the right side would cause an error.
Python also accepts a chained comparison such as 0 <= age < 18. It means the same as 0 <= age and age < 18.
Strings can be compared with == too. The check "yes" == "yes" gives True, and "Yes" == "yes" gives False, because capital letters count as different characters.
Worked example¶
Line by line, this is what Python does:
score = 72stores the integer 72 under the namescore.passed = score >= 50checks whether 72 is at least 50. It is, so the result isTrue, and the namepassedstores that boolean.print(passed)showsTrue. Python writes booleans with a capital letter.print(score == 100, score != 100)evaluates two comparisons, which giveFalseandTrue. The output isFalse True.print(not passed)flipsTruetoFalse, so the output isFalse.
The full output is:
Try it¶
Each block checks its results with assert. If a check is wrong, the block stops with an AssertionError.
The first check in the last block works only because and stops early. When divisor is 0, the left side is False, so 10 / divisor is never evaluated and no ZeroDivisionError appears.
Common mistakes¶
-
Using a bare number as a second condition. The following check passes for any value of
score:Python reads
or 3as a second operand. Any non-zero number counts asTrue, so the expression is alwaysTrue. Writeassert score == 2 or score == 3instead. -
Comparing a string with a number using
<. Writingprint("10" < 9)gives:Only values of compatible types can be ordered with
<. Convert the text withint("10")first. -
Leaving out the left side of a second comparison. Writing
print(age >= 18 and <= 65)gives:Each side of
andneeds a full comparison, so writeage >= 18 and age <= 65. -
Expecting
==between a string and a number to beTrue. The checkassert "5" == 5fails:The text
"5"and the integer5are different types, so==givesFalse. This is the same mistake you saw in the variables lesson.
Practice¶
- Write an
assertthat checks 12 is greater than or equal to 12, and another that checks 12 is not less than 10. - Store 25 in a variable named
x. Write anassertthat checksxis greater than 20 and less than 30. - Given
temperature = -3, write oneassertthat usesorto check the temperature is below 0 or above 35. - Given
a = 4andb = 9, write oneassertthat checks exactly one ofa > 5andb > 5isTrue. Hint: compare the two booleans with!=. - Stretch: write an
assertthat checks0 < x <= 100isTruewhenxis 100. Then write anassertthat checks the same chained comparison isFalsewhenxis 101.
Solution
-
python assert 12 >= 12 assert not (12 < 10) -
python x = 25 assert x > 20 and x < 30 -
python temperature = -3 assert temperature < 0 or temperature > 35 -
python a = 4 b = 9 assert (a > 5) != (b > 5)
The first comparison is False and the second is True. They differ, so != gives True.
python x = 100 assert 0 < x <= 100 x = 101 assert not (0 < x <= 100)
Recap¶
- A comparison gives
TrueorFalse. The operators are==,!=,<,<=,>, and>=. andneeds both sides to beTrue,orneeds one, andnotflips a boolean. Bothandandorstop early when the result is known.- Ordering with
<between a string and a number raises aTypeError, while==between them givesFalse.