Python Boolean operation return value is not always bool type

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

Python Boolean operation return value is not always bool type
python Boolean operation does not return a Boolean value
[Python] Boolean operator (or / and) does not return Boolean value
Python memo using perl-Dictionary type (case is not valid)
Python round is not strictly round
pypy bool type is slow
What to do when the value type is ambiguous in Python?
[python] week1-3: Number type and operation
python note: when easy_install is not available
[Python] Name Error: name'urlparse' is not defined
Python learning basics ~ What is type conversion? ~
[python] [meta] Is the type of python a type?
[Python] Invert bool value in one line
String → Bool value conversion in Python Consideration