Python bool() Function
The bool()
function converts a value to a boolean value i.e. one of True
or False
.
If the value is not specified, the method returns False
.
Syntax
bool(value)
bool() Parameters
Python bool()
function parameters:
Parameter | Condition | Description |
---|---|---|
value | Optional | Any object (like Number, List, String etc.), Any expression (like x > y, x in y). |
bool() Return Value
Python bool()
function returns:
False
: if argument is empty,False
,0
orNone
True
: if argument is any number (besides0
),True
or a String
Falsy Values in Python
Falsy values are those that evaluate to False in a boolean context:
- Constants defined to be false:
None
andFalse
. - Zero of any numeric type: Integer (
0
), Float (0.0
), Complex (0j
),Decimal(0)
,Fraction(0, 1)
. - Empty sequences and collections: Lists (
[]
), Tuples (()
), Dictionaries ({}
), Sets (set()
), Strings (""
),range(0)
- Any custom object for which the
__bool__()
method is defined to returnFalse
, or the__len__()
method returns0
when__bool__()
is not defined.
Examples
Examples of bool()
function on falsy values:
print(bool(0)) # Output False
print(bool([])) # Output False
print(bool(0.0)) # Output False
print(bool(None)) # Output False
print(bool(0j)) # Output False
print(bool(range(0))) # Output False
Examples of bool()
function on truthy values:
print(bool(1)) # Output True
print(bool([0])) # Output True
print(bool([1, 2, 3])) # Output True
print(bool(10)) # Output True
print(bool(3+4j)) # Output True
print(bool(range(2))) # Output True