I. Basic Concepts of the Boolean Type
The Boolean type is used to represent the results of logical judgments and has only two values:
True: logical trueFalse: logical false
Python uses the built-in type bool to represent Boolean values.
is_valid = True
is_empty = False
print(type(is_valid)) # <class 'bool'>
print(type(is_empty)) # <class 'bool'>
Boolean values usually appear in the following scenarios:
| Scenario | Example |
|---|---|
| Conditional evaluation | if user.is_active: |
| Loop control | while has_next: |
| Comparison operations | age >= 18 |
| Logical operations | is_valid and is_enabled |
| State flags | is_deleted = False |
| Function return values | return result is not None |
The Boolean type may seem simple, but it is closely related to Python's object model, integer type, truth-value protocol, and logical operation mechanisms.
II. Inheritance Relationship of the bool Type
In Python, bool is a subclass of int.
print(issubclass(bool, int)) # True
print(isinstance(True, bool)) # True
print(isinstance(True, int)) # True
Its type relationship is as follows:
object
└── int
└── bool
This means Boolean values have some of the behaviors of integers.
1. Boolean Values Correspond to Integer Values
In numeric operations:
Trueis equivalent to the integer1Falseis equivalent to the integer0
print(int(True)) # 1
print(int(False)) # 0
print(True + True) # 2
print(True + False) # 1
print(False * 10) # 0
Boolean values can participate in arithmetic operations, but this does not mean they should be used as ordinary integers.
2. bool Is an Immutable Type
True and False are built-in Boolean constants in Python; they cannot be reassigned or have their internal state modified.
value = True
# True = False
# SyntaxError
You cannot rebind a Boolean value to another value, nor can you change its logical state by modifying the object.
3. bool Has Only Two Instances
In a normal Python program, the bool type has only two built-in instances:
print(True is True) # True
print(False is False) # True
print(True is False) # False
You should not create other Boolean objects through the constructor to express different states.
print(bool(1)) # True
print(bool(0)) # False
print(bool("hello")) # True
The role of bool() is to return the existing True or False according to the object's truth-value rules.
III. The Concept of Truth Value
Python does not require conditional expressions to return the bool type.
In contexts that require evaluating logical conditions, such as if, while, and, or, and not, Python evaluates truth or falsehood according to the object's truth-value rules.
This mechanism is called truth value testing.
For example:
if "hello":
print("条件成立")
if []:
print("不会执行")
if 100:
print("条件成立")
The string, list, and integer here are not of type bool, but they can participate in conditional evaluation.
1. Core Rules of Truth Value Evaluation
The truth value of a Python object is mainly determined by two special methods:
__bool__()__len__()
Evaluation order:
- If the object defines
__bool__(), it is called first. - If
__bool__()is not defined but__len__()is, the decision is based on length. - If neither method is defined, the object is true by default.
Specific rules:
| Object Behavior | Truth Value Result |
|---|---|
__bool__() returns True |
True |
__bool__() returns False |
False |
No __bool__(), __len__() returns 0 |
False |
No __bool__(), __len__() returns a positive integer |
True |
| Neither method is defined | True |
Note: __bool__() must return an actual bool object; it cannot return an integer or another object.
__len__() must return a non-negative integer; if it returns a negative number or an invalid type, an exception will be raised.
2. Built-in Falsy Objects
Common falsy values in Python include:
| Object | Description |
|---|---|
False |
Boolean false value |
None |
Null value object |
0 |
Integer zero |
0.0 |
Floating-point zero |
0j |
Complex zero |
'' |
Empty string |
[] |
Empty list |
() |
Empty tuple |
{} |
Empty dictionary |
set() |
Empty set |
range(0) |
Empty range object |
Example:
values = [
False,
None,
0,
0.0,
0j,
"",
[],
(),
{},
set(),
range(0),
]
for value in values:
print(repr(value), bool(value))
Although these objects have different types, they are all evaluated as false in a boolean context.
3. Non-empty Objects Are Usually True
Common truthy objects include:
print(bool(1)) # True
print(bool(-1)) # True
print(bool(0.001)) # True
print(bool("0")) # True
print(bool("False")) # True
print(bool([0])) # True
print(bool({"a": None})) # True
Pay special attention to the following:
0is falsy, but the string"0"is truthy.Falseis falsy, but the string"False"is truthy.- The empty list
[]is falsy, but a list containing one element,[0], is truthy.
Truth value testing focuses on the object's own truth-value rules, not on whether the elements inside the object are true.
IV. bool() and Truth Value Conversion
The built-in function bool() is used to convert any object to a boolean value.
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("Python")) # True
print(bool([])) # False
print(bool([0])) # True
Essentially, it performs a truth value test and returns the corresponding boolean result.
1. bool() Is Not a String Parser
A common mistake is thinking that bool() can directly parse the true/false meaning of a string.
print(bool("True")) # True
print(bool("False")) # True
print(bool("0")) # True
print(bool("no")) # True
The reason is that none of these strings is an empty string.
bool() does not parse the string content; it only checks whether the string object is empty.
If you need to parse truthy or falsy strings from configuration files or user input, you should explicitly design conversion rules:
def parse_bool(value: str) -> bool:
normalized = value.strip().lower()
if normalized in {"true", "1", "yes", "on"}:
return True
if normalized in {"false", "0", "no", "off"}:
return False
raise ValueError(f"无效的布尔值: {value!r}")
print(parse_bool("True")) # True
print(parse_bool("OFF")) # False
In production code, you should not use bool(user_input) to interpret the truthiness semantics of user input.
2. Explicit Conversion and Implicit Truth Evaluation
The two forms have different semantics:
value = []
# Explicit conversion
result = bool(value)
# Implicit truthiness test
if value:
print("非空")
Calling bool() explicitly yields a Boolean value; a conditional statement performs a truth test directly in a Boolean context.
If you are only making a conditional check, you generally do not need an extra call to bool().
V. Comparison Operations and Boolean Results
Comparison operations are used to determine relationships between objects and typically return the bool type.
1. Common Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater than or equal to | a >= b |
<= |
Less than or equal to | a <= b |
is |
Same object identity | a is b |
is not |
Different object identity | a is not b |
in |
Membership | a in collection |
not in |
Non-membership | a not in collection |
Example:
age = 20
print(age >= 18) # True
print(age == 20) # True
print(age != 30) # True
print("Python" in "Python 3") # True
print("Java" not in "Python") # True
2. The Difference Between == and is
This is one of the most easily confused checks in Python.
==: Compares whether the values of two objects are equal.is: Compares whether two references point to the same object.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False
The two lists have the same contents, but they are different objects.
For None, identity comparison is recommended:
result = None
if result is None:
print("没有返回结果")
Do not use result == None in place of result is None.
3. Chained Comparison Syntax
Python supports chained comparisons:
age = 25
print(18 <= age < 60) # True
Equivalent logic:
18 <= age and age < 60
The middle expression in a chained comparison is evaluated only once, which differs from using two independent comparison expressions directly.
For example:
class Counter:
def __init__(self):
self.count = 0
def get_value(self):
self.count += 1
return 10
counter = Counter()
result = 5 < counter.get_value() < 20
print(result) # True
print(counter.count) # 1
This is also one reason chained comparisons are more reliable than repeatedly evaluating the expression.
6. Logical Operators
Python provides three logical operators:
and: logical ANDor: logical ORnot: logical NOT
1. and: Logical AND
and means that multiple conditions must all be true.
age = 25
has_license = True
if age >= 18 and has_license:
print("允许驾驶")
Logical rules:
| A | B | A and B |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
However, Python's and does not necessarily return a Boolean value.
Its actual rules are:
- Evaluate from left to right.
- If the left operand is false, return the left operand directly.
- If the left operand is true, continue evaluating the right operand and return the right operand.
print(0 and 100) # 0
print(10 and 100) # 100
print("" and "Python") # ''
print("A" and "B") # B
Therefore, and is essentially an operand-selecting operator with short-circuit behavior.
2. or: Logical OR
or means that as long as one condition is true, the overall result is true.
is_admin = False
is_owner = True
if is_admin or is_owner:
print("允许访问")
Logical rules:
| A | B | A or B |
|---|---|---|
| False | False | False |
| False | True | True |
| True | False | True |
| True | True | True |
Actual evaluation rules:
- Evaluate from left to right.
- If the left operand is true, return the left operand directly.
- If the left operand is false, continue evaluating the right operand and return the right operand.
print(0 or 100) # 100
print(10 or 100) # 10
print("" or "Python") # Python
print("A" or "B") # A
3. not: Logical NOT
not is used to negate a truth value, and the result is always of type bool.
print(not True) # False
print(not False) # True
print(not 0) # True
print(not 100) # False
print(not []) # True
print(not [1, 2]) # False
Unlike and and or, not always returns a Boolean value.
4. Operator Precedence
The precedence of logical operators, from highest to lowest, is:
notandor
For example:
result = not False and True or False
# Equivalent to
result = ((not False) and True) or False
print(result) # True
For complex conditions, it is recommended to use parentheses to clarify the expression structure:
if (age >= 18 and has_license) or is_admin:
print("允许操作")
Do not rely too heavily on the reader's memory of operator precedence.
7. Short-Circuit Evaluation Mechanism
Short-circuit evaluation is an important feature of Python logical operations.
When the result of an expression is already determined, Python no longer evaluates the remaining operands.
1. Short-Circuit Behavior of and
def check():
print("执行 check")
return True
result = False and check()
print(result)
Output:
False
check() will not execute, because the left side is already false, so the entire and expression must be false.
2. Short-Circuit Behavior of or
def check():
print("执行 check")
return False
result = True or check()
print(result)
Output:
True
check() likewise will not execute, because the left side is already true, so the entire or expression must be true.
3. Using Short-Circuiting for Safe Access
user = None
if user and user.is_active:
print("用户处于活动状态")
When user is None, and directly returns a false value and does not continue to access user.is_active, thereby avoiding an attribute access exception.
You can also use a default value:
username = user and user.name
But note: if user is a falsy object, username may end up being that object itself, not necessarily None.
If you need to strictly check for null, use:
username = user.name if user is not None else None
4. Short-Circuit Evaluation and Side Effects
Do not hide important side effects inside logical expressions.
is_valid = False
# Not recommended: whether the function executes depends on the left-hand condition
is_valid and save_to_database()
A clearer way to write it:
if is_valid:
save_to_database()
Short-circuit evaluation affects not only performance but also whether function calls, state changes, logging, and exceptions occur.
8. Truth Value Rules for Custom Objects
Python allows custom types to control their own truth value evaluation.
This is mainly implemented through __bool__() and __len__().
1. Using bool()
class User:
def __init__(self, active):
self.active = active
def __bool__(self):
return self.active
user1 = User(True)
user2 = User(False)
print(bool(user1)) # True
print(bool(user2)) # False
When if user1: executes, Python calls user1.__bool__().
You must ensure the return value is a bool:
class Invalid:
def __bool__(self):
return 1
# bool(Invalid()) will raise TypeError
Do not rely on Python automatically converting the return value of __bool__() into a boolean again.
2. Using len()
If __bool__() is not defined, Python can use __len__() to determine whether an object is true or false.
class Collection:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
a = Collection([])
b = Collection([1, 2])
print(bool(a)) # False
print(bool(b)) # True
An empty collection is false; a non-empty collection is true.
3. bool() Takes Precedence over len()
If both methods exist, __bool__() takes precedence.
class Example:
def __bool__(self):
return False
def __len__(self):
return 10
obj = Example()
print(len(obj)) # 10
print(bool(obj)) # False
len(obj) still returns the length, while bool(obj) uses the result of __bool__().
This means a custom type can make length and truth value express different semantics.
But in practical design, it is best to avoid unintuitive conflicts between the two.
4. Exception boundaries of truth-value methods
The following cases will trigger exceptions:
class NegativeLength:
def __len__(self):
return -1
# bool(NegativeLength()) raises ValueError
class InvalidBool:
def __bool__(self):
return "yes"
# bool(InvalidBool()) raises TypeError
When designing custom containers, follow these rules:
__bool__()returnsTrueorFalse.__len__()returns a non-negative integer.- Do not perform expensive I/O operations in truth-value checks.
- Do not let truth-value checks produce unpredictable side effects.
9. Common pitfalls in boolean evaluation
1. Null checks and truth checks are not the same thing
The following two ways of writing are not equivalent:
value = 0
if not value:
print("值为假")
if value is None:
print("值为空")
The first treats 0, False, "", [], etc. as false.
The second only checks whether the object is None.
If the business semantics require distinguishing "no value was provided" from "a zero value was provided", you must use is None.
2. You cannot use is to determine whether ordinary values are equal
a = 1000
b = 1000
print(a == b) # True