Python readings – Boolean

As part of my python reading, I am covering boolean datatype. Boolean basically can hold either True or False. A boolean variable can be simple defined as

#!/usr/bin/python

flag=True
print flag

Or it can be derived also from bool() function

flag = bool(random.randint(0, 1))
print Now the fate of the flag is decided randomly + str(flag)
Now the fate of the flag is decided randomly True (or False)

With boolean datatype, you can perform Boolean operation like this

print Some Boolean operations
print  using not operater
print flag, not flag
print And the output of  flag is not (not flag)
print flag is not (not flag)
print  And the output of   not flag is flag
print not flag is flag
using not operater
True False
And the output of   flag is not (not flag)  
True
And the output of   not flag is flag 
False
print Also let me try to see what happens if I apply arithmetics on boolean"
print  multiply flag with flag
print flag*flag

print  divide flag with flag 
print flag*flag

print  Add flag with flag 
print flag+flag

print  Subtract flag with flag 
print flag-flag

print bool(0+0j)
Also let me try to see what happens if I apply arithmetics on boolean
multiply flag with flag
1
divide flag with flag
1
Add flag with flag
2
Subtract flag with flag
0

Word of Caution:
Although its possible to use boolean with bit operation in some case, it can be misleading some times may
even throw some error in your code.

flag = True
print ~flag
-2

Though in this case it must be handled in a different,in many occasion function bool() can be very useful.

print bool()
print bool( )
print bool( test )
print bool('')
print bool(' ')
print bool(None)
print bool(0)
print bool(10)
print bool(-10)
print bool(0+0j)
False
True
True
False
True
False
False
True
True
False

You can get the entire source at github

Leave a Reply

Your email address will not be published. Required fields are marked *