Let’s Learn Python by studying another Python Built-in function. Bool function
in Python is used to get the Boolean Value True or False. Python bool() function return True or false of value passed in to the bool function parameter.
Syntax of bool
bool(item)
- bool is function name.
- item is any number, String, tuple, list etc. whose Boolean value has to be calculated.
Purpose of bool function
Bool function is used to check whether particular item has value or not. If it has some value, then it will return True. If it is empty, then it will return False.
Example of bool
#Python bool function example a=10 print (bool(a)) print (bool(b))
Output
True False
Explanation
- In above example, a, b are integers and having some values.
- when bool function is applied on a it returns True as variable a has some value 10.
- bool function on variable b returns False as variable b has 0 value.
When bool return True or False
Let’s discuss the cases when bool function returns True and False.
Let’s see the syntax
bool(item)
- if item is integer, then it will return True if number is non-zero. if number is 0 it will return False
- if item is String, then function will return True if string is non-empty, else it will returns False.
- In case of list, tuple, set dictionary etc. if these are non empty then bool will return True, else it will return False.
Let’s take one more example
#Python bool function example a=10 b=0 s1="some text" s2="" l1=[1,2] l2=[] t1=(1,2) t2=() print ("integer") print (bool(a)) print (bool(b)) print("***") print ("Strings") print (bool(s1)) print (bool(s2)) print("***") print ("list") print (bool(l1)) print (bool(l2)) print("***") print ("tuple") print (bool(t1)) print (bool(t2))
integer True False *** Strings True False *** list True False *** tuple True False
In above example, we can see the working Python bool function with list, tuple, String and Integer.