The bool()
function allows you to evaluate any value, and give you True
or False
in return,
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))
Evaluate two variables:
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
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.
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
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
.
The following will return False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
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
:
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
Try it Yourself »Track your progress - it's free!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4