Python - Data Type Boolean

Introduction

Python has an explicit Boolean data type called bool.

bool type has the values True and False as preassigned built-in names.

Literal

True and False are instances of bool, which is just a subclass of the built-in integer type int.

True and False behave exactly like the integers 1 and 0, except that they have customized printing logic.

They print themselves as the words True and False, instead of the digits 1 and 0.

bool accomplishes this by redefining str and repr string formats for its two objects.

You can treat True and False as though they are predefined variables set to integers 1 and 0.

Because True is just the integer 1 with a custom display format, True + 4 yields integer 5 in Python!

Demo

print( type(True) )
print( isinstance(True, int) )
print( True == 1 )        # Same value 
print( True is 1 )        # But a different object: see the next chapter 
print( True or False )    # Same as: 1 or 0 
print( True + 4 )         # (Hmmm)
#  w  ww  .j  a  va2 s  . c  om

Result

Python has Boolean type values.

Boolean type has predefined True and False objects.

Demo

print( 1 > 2, 1 < 2 )                    # Booleans 
print( bool('test') )                    # Object's Boolean value 
# from w w w.ja  va2s .  c  o  m
X = None                        # None placeholder 
print( print(X) )
L = [None] * 10                # Initialize a list of 10 Nones 
print(L)

Result

Related Topics