1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python論理演算の躓き

Last updated at Posted at 2020-05-20

Pythonのbool

前提として,Pythonでは0や空じゃないものはbool値がTrueになる.

bool(0) # False

bool(0.1) # True

bool("") # False

bool([""]) # True

逆に,TrueとFalseは1と0と同じように演算ができる.


True*1 # 1

False*1 # 0

True+0 # 1

True+True # 2

論理演算

Pythonに限った話ではないが,andとorは両辺を短絡評価している.

True and False # True

print("a") or print("b")
# a
# b

1 and print("b") # b

そしてPythonの論理演算は結果がboolに限らない.


100 and 200 # 200

200 and 100 # 100

100 or 200 # 100

200 or 100 # 200

and,orではなく&,| を利用するとビット演算になる.

True & False # False

True & 1 # 1

True & 2 # 0

123 & 125 # 121
1
1
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?