Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to evaluate values and variables using bool() in Python

Onyejiaku Theophilus Chidalu

Overview

To evaluate a value in Python in order to return a True or False, we use the bool() function.

Syntax

The syntax of the bool() function is:

bool([value])

Parameter values

The bool() function takes a single parameter value that needs to be evaluated. It converts the given value to either True or False.

Return value

This function returns a boolean value (True or False).

Evaluating a string and a number

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))
Implementing the bool() function

Explanation

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.

Evaluating variables

The bool() function can also be used to evaluate variables. Let’s run the code given below:

x = "Hello World"
y = 10

print(bool(x))
print(bool(y))

Explanation

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 string
print(bool("abc"))

# for a number
print(bool(100))

# for a list
print(bool(["apple", "cherry", "banana"]))

Explanation

In the output, we can see that all the values returned True, just as we stated they would earlier.

Empty values

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 value
print(bool(False))

# for None value
print(bool(None))

# for zero value
print(bool(0))

# for an empty string
print(bool(""))

# for an empty tuple
print(bool(()))

# for an empth list
print(bool([]))

# for an empty dictionary
print(bool({}))

Explanation

We can see that they all evaluated to False, just like we asserted they would.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring