The bool()
function in Python is used to convert a value to a Boolean (True or False) value. In this article, I will show you some examples on how to use the bool()
function.
1. Python bool() Function Examples.
1.1 Example 1.
- Using
bool()
with integers.>>> print(bool(0)) False >>> print(bool(1)) True >>> print(bool(-1)) True >>> >>> print(bool(10)) True >>> print(bool(-10)) True
- In this example,
bool()
is used to convert integers to Boolean values. Any non-zero integer will be converted toTrue
, while zero will be converted toFalse
.
1.2 Example 2.
- Using
bool()
with strings.>>> print(bool("")) False >>> print(bool(" ")) True >>> print(bool("hello")) True
- In this example,
bool()
is used to convert strings to Boolean values. An empty string will be converted toFalse
, while any non-empty string will be converted toTrue
.
1.3 Example 3.
- Using
bool()
with lists.>>> print(bool([])) False >>> >>> print(bool([1,2,3])) True
- In this example,
bool()
is used to convert lists to Boolean values. An empty list will be converted toFalse
, while any non-empty list will be converted toTrue
.
1.4 Example 4.
- Using
bool()
with None.>>> print(bool(None)) False
- In this example,
bool()
is used to convertNone
to a Boolean value.None
will be converted toFalse
.
1.5 Example 5.
- Using
bool()
with functions.>>> def foo(): ... return 1 ... >>> def bar(): ... return None ... >>> print(bool(foo())) True >>> print(bool(bar())) False
- In this example,
bool()
is used to convert functions to Boolean values. - Any function will be converted to
True
, regardless of its return value. - Note: In Python, several values are considered “falsey” and will be converted to
False
bybool()
. - These include
False
,0
,None
, empty sequences (e.g.,""
,[]
,()
), and empty mappings (e.g.,{}
). - All other values are considered “truthy” and will be converted to
True
.