The bool class in Python


bool class in Python

They are the only possible values for the bool class.

Here is a program that shows the data type.

print(type(True))
print(type(False))
Output 

<class 'bool'>
<class 'bool'>

The C language didn't have a boolean data type. 0(zero) was false and everything else true. Python bool class is very similar.
bools can be created in many different ways using the bool constructor. Basically anything that has a value is True and everything else is False.
Look up the following constructor calls and their outputs.


b=bool()
print(b)
Output

False
  • b=bool(0)
    print(b)
Output

False
  • b=bool(None)
    print(b)
Output

False
  • b=bool("")
    print(b)


Output


False

  • b=bool([])
    print(b)
Output

False
  • b=bool([0])
    print(b)
Output

True
  • b=bool([[]])
    print(b)
Output

True

These examples should be sufficient to illustrate the point. Everything that doesn't have a value(is None) is False and everything that has a value is True.

Let us check the members of the bool class. This, as we all know is one using the dir() function. Here is the program and output.

details=dir(bool)
print(details)
or
details=dir(True)
print(details)
or
details=dir(False)
print(details)


Output




['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

To find the super classes of bool we can use
  • details=bool.mro()
    print(details)

Output

[<class 'bool'>, <class 'int'>, <class 'object'>]

We will try out some if else problems in the next post.4





Post a Comment

0 Comments