6
5

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】変数の作成時にandとorを使う

Posted at

andとorの知らなかった使い方

論理演算子and, orでは、True, Falseなどのbool型を出力するだけでなく、条件によって数値や文字列、リストなども出力できる。

条件

式 x and y は、まず x を評価します; x が偽なら x の値を返します; それ以外の場合には、 y の値を評価し、その結果を返します。
式 x or y は、まず x を評価します; x が真なら x の値を返します; それ以外の場合には、 y の値を評価し、その結果を返します。
6. 式 (expression) — Python 3.8.3 ドキュメント

偽(False)とみなされるオブジェクトは以下の通りである
  • bool型のFalse
  • None
  • 数値(int型やfloat型)の0, 0.0
  • 空の文字列''
  • 空のコンテナ(リスト、タプル、辞書など)[], (), {}

x = 5  # True
y = 0  # False

print(x and y)
# 0

print(x or y)
# 5

print(not x)
# False
x = 10  # True
y = 100  # True

print(x and y)
# 100

print(y and x)
# 10

print(x or y)
# 10

参考サイト
[https://note.nkmk.me/python-boolean-operation/:embed:cite]

6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?