bool¶Python has a type bool for Boolean values. Unlike types int, float, and str, which have thousands of values, type bool has only two values: True and False.
Here are some examples of expressions that produce Booleans:
4 == 5.6
5 == 5
6.7 > 2
4.5 <= 9.3
27.4 != 27.5
In the code above, we used several of Python's relational operators. Here is a summary:
Equal to: ==
Not equal to: !=
Greater than: >
Greater than or equal to: >=
Less than: <
Less than or equal to: <=
There are three Boolean operators (the operands to these operators are type bool): not, and, and or.
not True
not False
Operator and evaluates to True if and only if both operands are True.
True and True
True and False
False and True
False and False
Operator or evaluates to True if and only if at least one operator is True.
True or True
True or False
False or True
False or False
Note: the Boolean operator or isn't quite the same as the English "or".
In English, "For dessert, I'll have pie or I'll have ice cream", means that I'll only have one dessert.
In Python, it means that I'll have at least one dessert.
Consider this code fragment:
grade1 = 80
grade2 = 90
not grade1 >= 50 or grade2 >= 50
What value does the expession produce: True or False?
The order of precedence for Boolean operators is not, and, and or.
To make the order clear, we can add parentheses:
(not grade1 >= 50) or (grade2 >= 50)
We can also use parentheses to change the order of operations:
not ((grade1 >= 50) or (grade2 >= 50))
Write an English description of the situation in which the following code produces True:
not grade1 >= 50 or grade2 >= 50.
How do you express the English "I'll have pie or I'll have ice cream, but not both"? Define two Boolean variables:
pie = False
ice_cream = True
Write a Python expression that evaluates to True if and only if exactly one of pie and ice_cream refers to True.