Python Boolean Data Type


Boolean or bool is a built-in data type in the python programming language. It can have two possible values –

  1.   True
  2.  False

These are equivalent to 1 and 0 respectively, the values that are used in languages like c or c++.  It is generally associated with conditional statements. Either a condition will be true or false on the basis of this different actions are taken by changing the control flow.

For example –

a=10
b=15

# Check whether a and b are equal or not
if a==b:
 print ("a and b are equal")
else:
 print("a and b are not equal")

When you run this program first condition will be checked that whether a and b are equal or not. You can see the output in the image below –

Since both variables contain different values the condition will become false and the statement under else will be executed.

Booleans are numeric type in Python

The bool type is a subclass of int class which is the standard integer type in Python. You can perform all the arithmetic operations on them as well. Even you can compare them to numbers.

For example –

# Statement 1
print(False*True+True)
# Statement 2
print(False/(True+True))

Here statement 1 will print 1 and statement 2 will print 0.0 as the output. You can check this by executing it on your system.

True and False values in Python

In Python, the numeric value zero (integer or fraction), empty strings, null value (None), empty containers such as list, set, etc are considered as false.

All other values are considered true.

You can check this by using bool() which will evaluate and return true or false. Now see the code below.

# The given statements will print False as output
print (bool(0))
print (bool(None))
print (bool(""))
print (bool([]))
# The following statements will print True as output
print(bool(2))
print(bool("xyz"))
print(bool(2))
print(bool(["abc","bcd"]))

Now see the output in the image below –

Functions returning a boolean value

In Python, there are many functions that can also return true or false for example isinstance() function which can be used to check a certain type of data type.

x=15.3
print(isinstance(x, float))

Since 15.3 is a float value this code will print True as the output.

Next, we will learn and work with the binary type of data in Python.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.