Sub topic 1
The bool type: True and False
Prerequisites
Assume you know Python variables, functions, if statements, and built-in types such as integers, strings, lists, and dictionaries.
The `bool` type: `True` and `False`
bool is Python's type for logical values. It has exactly two instances: True and False. Conditions such as comparisons produce values of this type.
is_ready = 3 < 5
print(is_ready) # True
print(type(is_ready)) # <class 'bool'>bool is a subclass of int. Therefore, True behaves like 1 and False behaves like 0 in arithmetic. Use this deliberately, not as a substitute for clear code.
print(True + True) # 2
print(False * 10) # 0
print(isinstance(True, int)) # TrueTruthiness: what counts as true or false
Truthiness is the rule Python uses when it needs a condition. The following values are false:
FalseNone- numeric zero, such as
0and0.0 - empty strings and containers, such as
"",[],{}, and()
Most other objects are true, including non-empty containers and the string "0".
values = [0, 1, "", "0", [], [0], None]
for value in values:
print(repr(value), bool(value))bool(value) makes this test explicit. An if statement performs the same conversion automatically.
items = []
if not items:
print("The list is empty")Comparison operators
Comparison operators return booleans:
x = 5
print(x == 5) # True
print(x != 3) # True
print(1 < x) # True
print(x >= 5) # True
print("apple" < "banana") # True
print([1, 2] == [1, 2]) # True== tests whether values are equal. Operators such as < and > order compatible values. Comparing incompatible types may raise TypeError.
Chained comparisons
Python lets you combine adjacent comparisons:
age = twenty = 20
print(18 <= age < 65) # TrueThis means 18 <= age and age < 65. Python evaluates age only once. Chaining is usually clearer than repeating the variable.
Exercise
What do bool([]), bool([0]), and 1 < 3 <= 3 return?
Show answer
They return False, True, and True.