5.3. Boolean Expressions¶
A boolean expression makes a comparison and returns one of the boolean
To make a decision within our code, a boolean expression is used as the
condition. A condition is a comparison that can be called correct
True) or incorrect (
5.3.1. Testing for Equality¶
The equality operator,
==, compares two values and returns
False depending on whether the values are identical.
1 2 3 4 5 6
num = 37 other_num = 40 print(5 == 5) print('abc' == 'def') print(num == other_num - 3)
True False True
In line 4, the two values are equal, so the expression evaluates to
In the line 5, the string
abc is not equal to
def, so we get
Line 7 compares the result of
other_num - 3 with the value stored in
A common error is using a single equals sign (
=) instead of a double
==) when comparing two values. We call
assignment operator, but
== is a comparison operator.
- To set the value of a variable, use
name = 'Mae').
- To compare values, use
name == other_name).
An equality test is symmetric, meaning that we can switch the places of the
two values and get the same the result. If
num == 7 is
7 == num is also
True. However, an assignment statement is NOT
num = 7 works while
7 = num does not.
220.127.116.11. Try It!¶
Use the simple code editor below to explore flipping an assignment statement:
5.3.2. Other Comparisons¶
== operator is one of seven common comparison operators.
Remember: The values on either side of an operator are called operands.
|Not equal (
|Greater than (
|Less than (
|Greater than or equal (
|Less than or equal (
5.3.3. Check Your Understanding¶
Which of the following are boolean expressions? Select ALL that apply.
- 3 <= 4
- 3 + 4
- "DogCat" == "dog" + "cat"
- text = 'Rutabagas!'