Python - Booleans


In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False.

>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)

A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version of complex() function.

If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0.

a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)

On running this code, you will get the following output

bool to int: 1
bool to float: 0.0
bool to complex: (1+0j)
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements