CLOSE

   python  library functions  
   Technology    Programming

Python bool() Method - Python Library Function

           
 AUGUST 2, 2019   by vineelpynam

In this article, we will see about python bool() method. This method converts a vlaue into a boolean value that is either true or false, based on standard truth testing procedure.

bool method in python

Below is the syntax for python bool() function

bool( X )
# X can be anything like list, string, empty value etc.

This bool() in python generally takes only one parameter as an input on which the standard truth testing procedure will be applied.

If no parameter is passed, then it return false by default

So, passing the parameter to bool() method is optional. It is upto you whether to add, or leave the parameter.

  • If a True Value is passed, it returns True.
  • If A False value is passed, it return False.

Let's see some cases when the bool() returns False as an input.

1. If a False value is passed.

2. If an empty value(None) is passed.

3. If Zero of any numeric type is passed. Ex: 0, 0.0 etc.

4. If empty sequence is passed. Ex: [], (), '' etc.

5. If empty mapping is passed. Ex: {}

6. Objects of Classes which has __bool__() or __len()__ method which returns 0 or False

Except above 6 cases, in all other remaining cases bool() method returns True


# empty list (Sequence)
check = []
print( bool(check) )

# A True bool is passed
check = True
print( bool(check) )

# An Empty Mapping 
check = {}
print( bool(check) )

# Zero Value (by default zero denotes false)
check = 0.0
print( bool(check) )
 
# None (no value is passed)
check = None
print( bool(check) )

# A string is passed
check = 'Study Tonight'
print( bool(check) )

After executing the program, the output will be:

False
True
False
False
False
True



Conclusion:

Pheww! This is it. I hope that you enjoyed the post and learned about the bool() python library function. If you feel that this post is useful, please share it with your friends and colleagues.

Thanks for reading it till the end.


SHARE YOUR THOUGHTS WITH US!