4.1. Boolean expressionsΒΆ
A boolean expression is an expression that is either
true or false. The following examples use the operator ==
,
which compares two operands and produces True
if they are
equal and False
otherwise:
True
and False
are special values that belong
to the class bool
; they are not strings:
The ==
operator is one of the comparison
operators; the others are:
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y
Although these operations are probably familiar to you, the Python
symbols are different from the mathematical symbols for the same
operations. A common error is to use a single equal sign
(=
) instead of a double equal sign (==
).
Remember that =
is an assignment operator and
==
is a comparison operator. There is no such thing as
=<
or =>
.
- True
- True and False are both Boolean literals.
- 3 == 4
- The comparison between two numbers via == results in either True or False (in this case False), both Boolean values.
- 3 + 4
- 3 + 4 evaluates to 7, which is a number, not a Boolean value.
- 3 + 4 == 7
- 3 + 4 evaluates to 7. 7 == 7 then evaluates to True, which is a Boolean value.
- "False"
- With the double quotes surrounding it, False is interpreted as a string, not a Boolean value. If the quotes had not been included, False alone is in fact a Boolean value.
Q-3: Which of the following is a Boolean expression? Select all that apply.
- x = y
- Try again. This reassigns the value of y to x.
- x != y
- Try again. This means that x is not equal to y.
- x == y
- Try again. This means that x and y have the same value, but it does not mean they are the same object.
- x is y
- This means that x and y are the same object, not just the same value.
- x is not y
- Try again. This means that x and y are not the same object. This can be true if x and y have the same value, but are stored in different objects.
Q-4: Which of the following comparison operators is used to check if x and y are the same object?
- >
- 783 > 206 is True.
- <=
- Try again. 783 <= 206 is False.
- True
- Try again.
- !=
- Correct! 783 != 206 is True.
- is not
- Correct! 783 is not 206 is True.
Q-5: What operator makes 783 ___ 206
true? Select all that apply.