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)
True
>>> bool(1)
True
>>> bool(0)
False
>>> bool('Saki')
True
>>> bool('')
False
>>> bool(3.14)
True
>>> bool(-9.7)
True

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)
1
>>> int(False)
0
>>> str(True)
'True'
>>> str(False)
'False'
>>> float(True)
1.0
>>> float(False)
0.0

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
False
>>> x != y
True
>>> x > y
True
>>> x < y
False

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!