C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: With the expressions in the second part of the example, we could omit the "bool" keyword and we would still have the same results.
Python program that uses bool
# Compute bools based on expressions and constants.
value1 = bool(2 == 3)
print(value1)
value2 = bool(None)
print(value2)
value3 = bool("cat")
print(value3)
print()
# Compute bools based on these variables.
a = 10
b = 10
value4 = bool(a == b)
print(value4)
value5 = bool(a != b)
print(value5)
value6 = bool(a > b)
print(value6)
Output
False
False
True
True
False
False
Here: An instance of the Box class evaluates to True only if the "value" field is equal to 1. All other values will result in False.
Python program that uses class, bool def
class Box:
def __init__(self, value):
# Initialize our box.
self.value = value
def __bool__(self):
# This returns true only if value is 1.
if self.value == 1:
return True
else:
return False
# Create Box instances.
# ... Use bool on them.
box = Box(0)
result = bool(box)
print(result)
box = Box(1)
result = bool(box)
print(result)
box = Box(2)
result = bool(box)
print(result)
Output
False
True
False
Tip: In good Python code we focus on meaning, not lower-level constructs. The bool here is probably best left out.
Python program that uses bool expressions
value = 5
# Both of these expressions evaluate to a bool.
# ... The bool keyword is not required.
correct = value == 5
correct_bool = bool(value == 5)
# Print results.
print(correct)
print(correct_bool)
Output
True
True
Python program that uses bool, no arguments
# These evaluate to false.
print(bool())
print(bool(None))
# The inner bool returns value.
print(bool(bool()))
# A string evaluates to true.
print(bool("a"))
Output
False
False
False
True
Quote: The bool class is a subclass of int. It cannot be subclassed further. Its only instances are False and True (see Boolean Values).
Built-in Functions: python.org