Python Evaluate Booleans
Evaluate Values
The bool()
function allows you to evaluate
any value, and give you
True
or False
in return,
Most Values are True
Almost any value is evaluated to True
if it
has some sort of content.
Any string is True
, except empty strings.
Any number is True
, except
0
.
Any list, tuple, set, and dictionary are True
, except
empty ones.
Example
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Try it Yourself »
Some Values are False
In fact, there are not many values that evaluates to
False
, except empty values, such as ()
,
[]
, {}
,
""
, the number
0
, and the value None
.
And of course the value False
evaluates to
False
.
Example
The following will return False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Try it Yourself »
One more value, or object in this case, evaluates to
False
, and that is if you have an object that
is made from a class with a __len__
function that returns
0
or
False
:
Example
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
Try it Yourself »
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.