Python bool() Function
bool()It is a built-in function in Python used to convert values to Boolean values.
Boolean values have only two possibilities:True(True) orFalse(False).
Word Definition: boolIt is the abbreviation for boolean, representing the 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 value.
Function Description
- Return Value: Returns
TrueorFalse。 - False values: The following values are False when converted to Boolean:
None、False、0、""、()、[]、{}、frozenset()。
Examples
Example 1: Basic Usage
Example
# Convert from various types
print(bool(1)) # Output: True
print(bool(0)) # Output: False
print(bool(-1)) # Output: True
print(bool("")) # Output: False
print(bool("hello")) # Output: True
print(bool([])) # Output: False
print(bool([1, 2])) # Output: True
print(bool(None)) # Output: False
print(bool(True)) # Output: True
print(bool(False)) # Output: False
print(bool(1)) # Output: True
print(bool(0)) # Output: False
print(bool(-1)) # Output: True
print(bool("")) # Output: False
print(bool("hello")) # Output: True
print(bool([])) # Output: False
print(bool([1, 2])) # Output: True
print(bool(None)) # Output: False
print(bool(True)) # Output: True
print(bool(False)) # Output: False
Expected Output:
True False True False True False True False True False
Code Explanation:
- The number 0 is False, non-zero is True.
- An empty string is False, non-empty is True.
- An empty list is False, a non-empty list is True.
Example 2: Common Applications
Example
# Check if the list is empty
items = []
if bool(items):
print("List is not empty")
else:
print("List is empty") # Output: List is empty
# Check if the string has content
name = ""
if bool(name.strip()):
print(f"Hello, {name}")
else:
print("Please enter your name") # Output: Please enter your name
# Check if a value exists
data = {"name": "Tom"}
if bool(data.get("email")):
print("Has email")
else:
print("No email") # Output: No email
items = []
if bool(items):
print("List is not empty")
else:
print("List is empty") # Output: List is empty
# Check if the string has content
name = ""
if bool(name.strip()):
print(f"Hello, {name}")
else:
print("Please enter your name") # Output: Please enter your name
# Check if a value exists
data = {"name": "Tom"}
if bool(data.get("email")):
print("Has email")
else:
print("No email") # Output: No email
Expected Output:
List is empty
bool()Commonly used in conditional judgments to check whether a value exists or has content.
Other Extensions