170
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

三項演算子(Python)

 三項演算子を使うことで代入の条件分岐を一行でスマートに記述することができます。

用法

(変数) = (条件がTrueのときの値) if (条件) else (条件がFalseのときの値)

 例えば次のような条件によってxの値を分けたいとき

python
if n == 10:
    x = "OK"
else :
    x = "NG"

 
 これを三項演算子を用いて一行で表現すると次のようになります。

python
x = "OK" if n == 10 else "NG"
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
170
Help us understand the problem. What are the problem?