Python bool() Function
bool() is a built-in Python function that converts a value to a boolean.
A boolean has only two possible values:True(true) or False(false).
Word meaning: bool is short for boolean, denoting a logical value type.
Basic syntax and parameters
Syntax format
bool(x)
Parameter Description
- Parameter x:
- Type: any value
- Description: the value to convert to a boolean.
Function description
- Return Value: Returns
TrueorFalse。 - Falsy values: the following values are False when converted to a boolean:
None、False、0、""、()、[]、{}、frozenset()。
Example
Example 1: basic usage
Example
Convert from various types
(
bool
(
1
)
)
Output: True
(
bool
(
0
)
)
Output: False
(
bool
(
1
)
)
Output: True
(
bool
(
""
)
)
Output: False
(
bool
(
"hello"
)
)
Output: True
(
bool
(
[
]
)
)
Output: False
(
bool
(
[
1
,
2
]
)
)
Output: True
(
bool
(
None
)
)
Output: False
(
bool
(
True
)
)
Output: True
(
bool
(
False
)
)
Output: False
Expected output:
True
False
True
False
True
False
True
False
True
False
Code analysis:
- The number 0 is False; nonzero numbers are True.
- An empty string is False; a non-empty one is True.
- An empty list is False; a non-empty list is True.
Example 2: common applications
Example
Check whether a list is empty
items
=
[
]
if
bool
(
items
)
:
(
"The list is not empty"
)
else
:
(
"The list is empty"
)
Output: The list is empty
Check whether a string has content
name
=
""
if
bool
(
name.
strip
(
)
)
:
(
f
"Hello, {name}"
)
else
:
(
"Please enter a name"
)
Output: Please enter a name
Check whether a value exists
data
=
{
"name"
:
"Tom"
}
if
bool
(
data.
get
(
"email"
)
)
:
(
"Has an email"
)
else
:
(
"No email"
)
Output: No email
Expected output:
列表为空
请输入名字
无邮箱
bool() Commonly used in conditionals to check whether a value exists or has content.
Python3 built-in function