Skip to main content

Bool

Properties​

>>> dir(bool)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

Definition​

A Boolean value (bool) is a logical value: True or False. It answers questions like “Is this statement correct?” For instance, 1 == 2 is False.

bool is a subclass of int, so in many circumstances booleans are evaulated like numbers.

Using booleans​

If a statement is true then it will evaluate to True. Conversely, if a statement is false then it will evaluate to False.

>>> 1 == 1
True

>>> 1 == 2
False

>>> "Hello" == "World"
False

>>> "Hello" == "Hello"
True

Types with falsy values​

The boolean value of an empty type will always be False.

TypeExampleNotes
boolFalseThe literal False itself
NoneTypeNoneRepresents “no value”
int, float, complex0, 0.0, 0jAny numeric zero
str""Empty string
list[]Empty list
tuple()Empty tuple
dict{}Empty dictionary
setset()Empty set
frozensetfrozenset()Empty frozen set
rangerange(0)Empty range object

Likewise a custom class that ony returns 0 or False will be falsy.

Types with truthy values​

The boolean value of a non-empty type will always be True.

TypeExampleNotes
boolTrueThe literal True
int, float, complex1, 3.14, -2+0jAny nonzero
str"Hello"Any non-empty string
list[1, 2, 3]Any non-empty list
tuple(1, 2)Any non-empty tuple
dict{"a": 1}Any non-empty dictionary
set{"x", "y"}Any non-empty set
frozensetfrozenset({1})Any non-empty frozen set
rangerange(1, 5)Any range with at least one value

Checking for truthiness​

The boolean value of a type can be checked by using the bool() function.

>>> bool("")
False

>>> bool(0)
False

>>> bool("99 problems but a bool aint one")
True

Operations: truth tables​

The and operator​

ExpressionResultExplanation
True and TrueTrueBoth values are true
True and FalseFalseOne is false
False and TrueFalseOne is false
False and FalseFalseBoth are false

The or operator​

ExpressionResultExplanation
True or TrueTrueAt least one is true
True or FalseTrueFirst value is true
False or TrueTrueSecond value is true
False or FalseFalseBoth are false

The not operator​

ExpressionResultExplanation
not TrueFalseNegates the value
not FalseTrueNegates the value

Dunder methods​

Dunder MethodOperationExample (normal syntax)Example (dunder call)
__bool__Truth valuebool(True) → TrueTrue.__bool__()
__and__Logical AND / Bitwise &True & False → FalseTrue.__and__(False)
__or__Logical OR / Bitwise |True | False → TrueTrue.__or__(False)
__xor__Logical XOR / Bitwise ^True ^ False → TrueTrue.__xor__(False)
__invert__Bitwise NOT~True → -2True.__invert__()
__eq__Equality comparisonTrue == False → FalseTrue.__eq__(False)
__ne__Inequality comparisonTrue != False → TrueTrue.__ne__(False)
__lt__Less thanFalse < True → TrueFalse.__lt__(True)
__le__Less than or equalTrue <= True → TrueTrue.__le__(True)
__gt__Greater thanTrue > False → TrueTrue.__gt__(False)
__ge__Greater than or equalTrue >= False → TrueTrue.__ge__(False)
__add__AdditionTrue + True → 2True.__add__(True)
__sub__SubtractionTrue - False → 1True.__sub__(False)
__mul__MultiplicationTrue * 5 → 5True.__mul__(5)
__int__Convert to integerint(True) → 1True.__int__()
__float__Convert to floatfloat(False) → 0.0False.__float__()
__index__Integer index value[10, 20][True] → 20True.__index__()
__str__String conversionstr(True) → 'True'True.__str__()
__repr__Representationrepr(True) → 'True'True.__repr__()
__hash__Hash valuehash(True) → 1True.__hash__()

Boolean methods​

All boolean methods are inherited from int.

as_integer_ratio​

Returns a tuple (numerator, denominator) representing the boolean as a fraction.

>>> True.as_integer_ratio()
(1, 1)

>>> False.as_integer_ratio()
(0, 1)

bit_count​

Returns the number of 1 bits in the integer representation of the boolean.

>>> True.bit_count()
1

>>> False.bit_count()
0

bit_length​

Returns the number of bits required to represent the boolean as an integer, excluding the sign bit.

>>> True.bit_length()
1

>>> False.bit_length()
0

conjugate​

Returns the complex conjugate of the boolean value. Since booleans are real-valued, this just returns the same integer value (1 or 0).

>>> True.conjugate()
1

>>> False.conjugate()
0

denominator​

Returns the denominator of the boolean when viewed as a rational number. It is always 1.

>>> True.denominator
1

>>> False.denominator
1

from_bytes​

Class method that returns a boolean created from a sequence of bytes. Any non-zero value becomes True; zero becomes False. It is the inverse of to_bytes.

>>> int.from_bytes(b"\x01", "big") != 0
True
>>> bool(int.from_bytes(b"\x00", "big"))
False

Note: from_bytes is defined on int; booleans use the same implementation via inheritance.


imag​

The imaginary part of the boolean when viewed as a complex number. Always 0.

>>> True.imag
0
>>> False.imag
0

numerator​

The numerator of the boolean when viewed as a fraction. True has numerator 1; False has numerator 0.

>>> True.numerator
1
>>> False.numerator
0

real​

The real part of the boolean when viewed as a complex number. This is the same as its integer value (1 or 0).

>>> True.real
1
>>> False.real
0

to_bytes​

Convert the boolean (as an integer) to a bytes object using a given length and byte order.

>>> True.to_bytes(1, "big")
b'\x01'
>>> False.to_bytes(1, "big")
b'\x00'