Basics

Booleans

Booleans represent truth values and combine with logical operators.

Use booleans for facts that are either true or false. Python spells the constants True and False.

Use and, or, and not to combine truth values. These operators read like English and short-circuit when possible.

Source

logged_in = True
has_permission = False

print(logged_in and has_permission)
print(logged_in or has_permission)
print(not has_permission)

Output

False
True
True
A AND BTFTFTFFF
`a and b` returns True only when both are True; otherwise it returns the first falsy value.

Comparisons produce booleans too, so they compose naturally with logical operators in conditions and validation checks.

Source

name = "Ada"
print(name == "Ada" and len(name) > 0)

Output

True

bool is a subclass of int, which is occasionally a footgun. True behaves as 1 and False as 0 in arithmetic, and isinstance(True, int) is True. When a function must reject booleans, exclude them explicitly with isinstance(value, int) and not isinstance(value, bool).

Source

print(isinstance(True, int))
print(True + True)
print(sum([True, True, False, True]))

def is_strict_int(value):
    return isinstance(value, int) and not isinstance(value, bool)

print(is_strict_int(True))
print(is_strict_int(1))

Output

True
2
3
False
True

Notes

See also

Run the complete example

Example code

Expected output

False
True
True
True
True
2
3
False
True

Execution time appears here after you run the example.