Boolean Expressions
Learning Objectives
- You can write Boolean expressions using comparison operators.
- You can combine Boolean expressions with
and,or, andnot. - You can distinguish
==(comparison) from=(assignment). - You can predict whether a Boolean expression evaluates to
TrueorFalse.
Before your programs can branch — do one thing in one situation and a different thing in another — they need a way to ask a question whose answer is yes or no. In Python, that kind of question is called a Boolean expression, and its answer is one of two values: True or False.
This chapter is about how to write those questions. The next chapter is about how to use them to make decisions.
True and False Are Values
True and False are values in Python, just like 5 or "hello". They are not strings, and they are not the words “true” and “false”. They are capitalized keywords, and Python is strict about the spelling.
print(True)print(False)print(3 < 5)This program prints True, False, and True on three lines. The third line is the interesting one: 3 < 5 is an expression that Python evaluates into the value True before it is printed.
You can store these values in variables:
is_long_session = Trueprint(is_long_session)These two values together are called Booleans, named after the mathematician George Boole.
Boolean values
0 / 5 points
Which line prints the Boolean value True, not the text "True"?
Comparison Operators
The most common way to produce a Boolean is with a comparison operator. Comparison operators compare two values and produce True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 3 == 3 | True |
!= | not equal to | 3 != 5 | True |
< | less than | 3 < 5 | True |
> | greater than | 3 > 5 | False |
<= | less than or equal to | 5 <= 5 | True |
>= | greater than or equal to | 3 >= 5 | False |
Comparison works on numbers the way you would expect. It also works on strings, but compares them character by character against their position in the alphabet (with lowercase and uppercase being different characters):
print("Math" == "math")print("Math" == "Math")This program prints False and then True. Case matters. So does whitespace: "Math" and "Math " (with a trailing space) are not equal.
Comparison results
0 / 5 points
What does this program print?
print(8 >= 8)print("math" == "Math")Common Source of Confusion: == vs =
One symbol is for comparing. The other is for assigning. They look almost identical, and the mistake of writing one when you meant the other is one of the most common beginner errors.
=is assignment. It puts a value into a variable.minutes = 60means “setminutesto60.”==is comparison. It asks whether two values are equal.minutes == 60means “isminutesequal to60?”
A useful trick: when you read == out loud, say “is equal to”. When you read = out loud, say “becomes”. Two completely different operations, two completely different words.
In the next chapter, you will start using if statements, where the difference matters a lot. Writing if minutes = 60: is a syntax error, and the error message Python gives you is the hint that you meant ==.
Assignment and comparison
0 / 5 points
Arrange the lines into a program that stores a value, compares it, and prints the Boolean result.
Combining Conditions with and, or, and not
Sometimes one condition is not enough. You want to know whether two things are both true, or whether at least one of them is true.
Python uses three keywords for this:
andis true only when both sides are true.oris true when at least one side is true.notflips the value:not TrueisFalse, andnot FalseisTrue.
Here are the rules in table form. They match how the words work in English most of the time.
A | B | A and B | A or B |
|---|---|---|---|
True | True | True | True |
True | False | False | True |
False | True | False | True |
False | False | False | False |
A natural use case in the study log is checking whether a session length is in a reasonable range. The following example also shows how Boolean expressions can be combined with comparison operators to make conditions easier to read:
minutes = 45in_range = minutes >= 15 and minutes <= 120print(in_range)This prints True, because 45 is both at least 15 and at most 120. If minutes were 5, the first part would be False, and and would make the whole expression False.
Python has its own shorthand for “is this value between two others”: you can write
15 <= minutes <= 120directly, which reads almost like math. Both forms work. Use whichever is clearer to you.
Negation with not
The not keyword flips a Boolean.
session_logged = Falseprint(not session_logged)This prints True. not is most useful in front of a comparison that would be awkward to write the opposite way:
if not subject == "Math": print("Different subject today.")Though in practice this exact example reads more clearly as subject != "Math". Use not when there is no neat operator for the opposite of what you mean, and use the direct comparison when there is.
Explain a combined Boolean condition
0 / 10 points
Consider this code:
subject = "Art"minutes = 25should_review = not subject == "Math" and minutes < 30print(should_review)Explain what the expression checks, what value it prints, and how not subject == "Math" could be written more directly.
Your answer should include:
- the value of
subject == "Math", - the value of
minutes < 30, - the final printed value,
- and the clearer comparison using
!=.
Some values in Python that are not technically True or False still act like one or the other when Python expects a Boolean.
- The empty string
""acts likeFalse. Any non-empty string acts likeTrue. - The number
0acts likeFalse. Any non-zero number acts likeTrue. - An empty list
[]acts likeFalse. (You will meet lists in Lists.) Any non-empty list acts likeTrue.
This is called truthiness. It is sometimes convenient — you will see why in while Loops — but it can also be a source of confusing bugs. For now, prefer explicit comparisons: write if minutes == 0 rather than if not minutes, even though both work.
Boolean variables and natural-language programming
0 / 5 points
In this exercises, there are draggable natural language blocks and a possibility to add your own custom written blocks. Drag the blocks to the “Program” area and then create your own custom blocks needed to solve the exercise. The program that you create should read in an integer from a user and compare it to 7, storing the outcome to the variable x. Based on the comparison outcome, the program should print “True” if the input number is greater than 7 and “False” otherwise.
Putting Several Conditions Together
The real power of Booleans appears when you stack several pieces.
subject = "Math"minutes = 45
is_focus_subject = subject == "Math" or subject == "Physics"is_solid_session = minutes >= 30 and minutes <= 90should_celebrate = is_focus_subject and is_solid_session
print(should_celebrate)This prints True. The program asks three small questions in turn, stores each answer in a variable, and then combines them.
You could write the whole thing as one long expression:
should_celebrate = (subject == "Math" or subject == "Physics") and (minutes >= 30 and minutes <= 90)This is fine for short expressions, but as soon as a condition has more than two parts, breaking it into named pieces makes it much easier to read and to debug. Named intermediate variables are one of the most useful habits in this chapter.
The parentheses in the one-line version above are not strictly required by Python —
andalready binds tighter thanor— but they make the grouping unambiguous to a reader. When in doubt, add them.
Check Your Understanding
- What is the difference between
=and==in Python? - What is the value of
3 < 5 and 5 < 3? - What is the value of
"Math" == "math", and why? - Rewrite this expression using a single comparison chain:
minutes >= 0 and minutes <= 60. - What is the value of
not (5 > 3)?