To evaluate a value in Python in order to return a True
or False
, we use the bool()
function.
The syntax of the bool()
function is:
bool([value])
The bool()
function takes a single parameter value
that needs to be evaluated. It converts the given value to either True
or False
.
This function returns a boolean value (True
or False
).
We can use the bool()
function to evaluate a string and a number. Let’s run the code given below:
print(bool("Hello World"))print(bool(10))
From the output of the code that is given above, we can see that our string and number were written correctly. Therefore, after evaluation from Python using the bool()
function, it returned True
for both.
The bool()
function can also be used to evaluate variables. Let’s run the code given below:
x = "Hello World"y = 10print(bool(x))print(bool(y))
The output of the code that is given above shows us that the variables we created were correctly written.
Moreover, a string is always True
, unless it is empty.
Numbers are True
, unless they are 0
. Tuples, lists, sets, and dictionaries all always return True
, except for when they are empty. Let’s look at the example given below:
# For a stringprint(bool("abc"))# for a numberprint(bool(100))# for a listprint(bool(["apple", "cherry", "banana"]))
In the output, we can see that all the values returned True
, just as we stated they would earlier.
The empty values, such as ()
, {}
, []
, ""
, 0
, false
, and None
, will return False
after evaluation.
Let’s look at the code for empty values:
# for false valueprint(bool(False))# for None valueprint(bool(None))# for zero valueprint(bool(0))# for an empty stringprint(bool(""))# for an empty tupleprint(bool(()))# for an empth listprint(bool([]))# for an empty dictionaryprint(bool({}))
We can see that they all evaluated to False
, just like we asserted they would.