LoginSignup
1
1

More than 3 years have passed since last update.

Python ブール演算の戻り値はbool型とは限らない

Posted at

Pythonでブール演算を行えるのはbool型だけではなく、戻り値もbool型とは限らない。

オブジェクトの真理値を確認するには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

左オブジェクトの真理値が真なら右オブジェクトを返す:


>>> 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 []
[]

左オブジェクトの真理値が偽なら左オブジェクトを返す:


>>> False and True
False
>>> [] and 'abc'
[]
>>> '' and [1,2,3]
''

>>> False and False
False
>>> [] and ''
[]
>>> '' and []
''

or

左オブジェクトの真理値が真なら左オブジェクトを返す:

>>> 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'

左オブジェクトの真理値が偽なら右オブジェクトを返す:

>>> False or True
True
>>> [] or 'abc'
'abc'
>>> '' or [1,2,3]
[1, 2, 3]

>>> False or False
False
>>> [] or ''
''
>>> '' or []
[]

not

bool型しか返さない。
オブジェクトの真理値が真ならFalse:


>>> not True
False
>>> not [1,2,3]
False
>>> not 'abc'
False

オブジェクトの真理値が偽ならTrue:


>>> not False
True
>>> not []
True
>>> not ''
True
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1