Booleans in Python (Logical Data Types)

"The computer is incredibly fast, accurate, and stupid. Man is incredibly slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation."- Leo Cherne

Did you read above quote? And do you know, how computers think? Computers are funny creatures, they think in terms of 0s and 1s i.e. Flase and True.

While python has several numeric data types, there is only one logical type, Booleans.

Booleans are built-in data type in python and there are only two values True or False.

Note that True and False both are capitalized unlike other programming languages.

If you inspect the type True and False using type() function you will get <bool> class which indicates Booleans.

See execution in python below:

>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

In python, you can convert any other entities like integers, floating point numbers, strings etc. to Boolean types using bool().

See execution in python below:

>>> bool(12)
>>> bool(1)
>>> bool(0)
>>> bool('Saki')
>>> bool('')
>>> bool(3.14)
>>> bool(-9.7)

In python, zero is converted to False while every other number is converted to True. And, except empty string every other string is converted to True.

Similarly, in python, you can convert Boolean type to other type.

See execution in python below:

>>> int(True)
>>> int(False)
>>> str(True)
>>> str(False)
>>> float(True)
>>> float(False)

Remember, python treats True as 1 and False as 0.

Booleans are commonly encountered when comparing two entities. For example suppose x = 9 and y = 7. To compare two number x and y we use different relational operators.

See execution in python below:

>>> x = 9
>>> y = 7
>>> x == y
>>> x != y
>>> x > y
>>> x < y

Self Contemplation Question?

  1. What will be the output of 7 + True in python?
  2. What will be the output of 'Dog' + False in python?
  3. What will be the output of 'Dog' + str(False) in python?
  4. What will be the output of 9.81 + True in python?

Post your answer in comment section below. We're always listening!