Step 1 of 8 · Reading · ~4 min
Learn
Making Decisions
Comparison and Boolean Logic
A comparison is an expression that produces a value, the same way 3 + 4 produces 7. The
value it produces is either True or False. By the end of this lesson you can build such
expressions, combine them with and, or and not, and print the result.
A comparison produces a value
Six operators compare two values and hand back a boolean.
The result is an ordinary value, so you can store it:
bool is a type of its own, alongside int and str. It has exactly two values and they are
spelled with a capital letter: True and False. Lowercase true is a NameError, and the
text "True" in quotes is a string, not a boolean.
One = assigns a value to a name; two == compare two values. Mixing them up is the oldest
beginner bug there is.
Text compares too, and it is picky
Text and numbers cannot be ordered against each other:
A line you read with input() is always text, so convert it with int() before you compare it
as a number.
in: is one piece of text inside another?
in looks for the piece anywhere in the text; == demands the whole thing. Different
questions, different answers.
and, or, not
A B A and B A or B
True True True True
True False False True
False True False True
False False False False
not grabs only what comes directly after it. To flip a whole combined expression, wrap that
expression in parentheses first:
Stored booleans combine exactly like the comparisons themselves:
Short-circuit evaluation
Python reads and and or left to right and stops the moment the answer is settled.
Neither inner print runs. That is what makes the guard count != 0 and total / count > 5
safe: when count is 0 the left side is already False, so the division never happens.
== versus is
== asks whether two values are equal. is asks whether two names refer to the very same
object. Use == for the comparisons in this course, and keep is for the one idiom
value is None.
Common mistakes
orwhere a range needsand:n >= 50 or n <= 200isTruefor every number on earth, because each number satisfies at least one half. The range test needsand.>where the boundary counts: with "between 50 and 200, both ends included",n > 50printsFalsefor exactly 50, which is supposed to be inside the range.inwhere==was meant:"go" in "golden"isTrue, but"go" == "golden"isFalse. The loose question saysTruewhere the strict one saysFalse.- Comparing a raw input line as a number: without
int(), the comparison raisesTypeErrorand your program dies before printing anything.
Your exercise
Print the four boolean checks described below, one per line. The starter reads both lines and
prints a placeholder on each output line; replace each placeholder with the comparison it names.
The one that catches most people is the fourth: not needs parentheses around the range it
flips.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…