PythonBuilt-in functions
bool()
Converts a value to True or False according to the rules of truthiness.
- Returns
TrueorFalse.
Example
#Python
print(bool(0), bool(42))
print(bool(""), bool("text"))
print(bool([]), bool([0]))
print(bool(None))
print(bool("False"))Resultsaved result, you can check it
False True
False True
False True
False
True
Definition and usage
#The bool() function returns True or False. These are falsy: False, None, zero of any numeric type, and empty collections and strings ("", [], {}, (), set()). Every other value is truthy.
Python applies the same rules in every condition: if my_list: works like if bool(my_list):. That lets you check briefly whether a string is non-empty or a list has items.
Watch out for strings: bool("False") and bool("0") are both True, because they are non-empty strings. Text from a user has to be compared explicitly, e.g. answer.lower() == "yes".
Syntax
#Syntax
bool(x)Parameters
#x
any value
The value to evaluate.
Good practices
#- In conditions, don't write
if bool(x):orif x == True:.if x:is enough. - The value
Truebehaves like the number 1:sum([True, True, False])gives 2.
Related entries
#Spotted a mistake or missing an example? Write to us.