It is not only the bool type that can perform Boolean operations in Python, and the return value is not always the bool type.
To check the truth value of an object bool ()
:
>>> bool(123)
True
>>> bool([1,2,3])
True
>>> bool('abc')
True
>>> bool({'a':1, 'b':2, 'c':3})
True
>>> bool((1,2,3))
True
>>> bool(0)
False
>>> bool([])
False
>>> bool('')
False
>>> bool({})
False
>>> bool(())
False
>>> bool(None)
False
and Returns the right object if the truth value of the left object is true:
>>> True and True
True
>>> [1,2,3] and 'abc'
'abc'
>>> 'abc' and [1,2,3]
[1, 2, 3]
>>> True and False
False
>>> [1,2,3] and ''
''
>>> 'abc' and []
[]
Returns the left object if the truth value of the left object is false:
>>> False and True
False
>>> [] and 'abc'
[]
>>> '' and [1,2,3]
''
>>> False and False
False
>>> [] and ''
[]
>>> '' and []
''
or
Returns the left object if the truth value of the left object is true:
>>> True or True
True
>>> [1,2,3] or 'abc'
[1, 2, 3]
>>> 'abc' or [1,2,3]
'abc'
>>> True or False
True
>>> [1,2,3] or ''
[1, 2, 3]
>>> 'abc' or []
'abc'
Returns the right object if the truth value of the left object is false:
>>> False or True
True
>>> [] or 'abc'
'abc'
>>> '' or [1,2,3]
[1, 2, 3]
>>> False or False
False
>>> [] or ''
''
>>> '' or []
[]
not Returns only bool type. False: If the truth value of the object is true
>>> not True
False
>>> not [1,2,3]
False
>>> not 'abc'
False
True if the truth value of the object is false:
>>> not False
True
>>> not []
True
>>> not ''
True
Recommended Posts