In Python, several types of values can be converted to boolean using the bool() function. Here are some common conversions:
-
Numbers:
- Non-zero numbers (e.g.,
1,-1,3.14) areTrue. - Zero (
0,0.0) isFalse.
- Non-zero numbers (e.g.,
-
Strings:
- Non-empty strings (e.g.,
"Hello"," "(space)) areTrue. - Empty strings (
"") areFalse.
- Non-empty strings (e.g.,
-
Lists, Tuples, Sets, and Dictionaries:
- Non-empty collections (e.g.,
[1, 2],(1,),{1},{'key': 'value'}) areTrue. - Empty collections (
[],(),set(),{}) areFalse.
- Non-empty collections (e.g.,
-
None:
- The value
NoneisFalse.
- The value
-
Custom Objects:
- By default, instances of user-defined classes are
True, unless the class defines a__bool__()or__len__()method that returnsFalseor0.
- By default, instances of user-defined classes are
Here are some examples:
print(bool(42)) # True
print(bool(0)) # False
print(bool("Python")) # True
print(bool("")) # False
print(bool([1, 2, 3])) # True
print(bool([])) # False
print(bool(None)) # False
These conversions are useful for controlling flow in conditional statements and loops. If you have more questions or need further examples, let me know!
