28 Aug 2013

Boolean Value of a Data Types in Python

Boolean values in python are True, False and None. While going through the pages of DiveIntoPython , i found a sentence which says that :

You can use virtually any expression in a boolean context.

then i thought ANY expression ?  so i tried following code :

if "poi":
     print "yes"    
else:
    print "no"

My first guess was that it should give error, since "poi" is not evaluates to be a boolean value. It didn't give any error and prints the "yes". but .....Why ?

Every datatype in python has a boolean associated value with it. So string, list , tuple and dictionary are all can be used in the boolean context.

Then what evaluates true or False for these data types ?

Well, whenever these data types are empty, their boolean value will be False.
>>var=""
>>bool(var)
False
Same is true for [], (), {} i.e. non-empty list, tuple and dictionary.

And when these data types are not empty having atleast one element , their boolean value will be True.
>>var="python"
>>bool(var)
True
Same is true for [3], (4,5), {"key": 3} i.e. non-empty list, tuple and dictionary.

For numbers ,
None evaluates to be False.
non-zero number evaluates to be True.
0 (or 0.0) evaluates to be False.





No comments:

Post a Comment