253
181

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 5 years have passed since last update.

三項演算子(Python)

Last updated at Posted at 2015-03-02

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

用法

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

 例えば次のような条件によってxの値を分けたいとき
python
if n == 10:
    x = "OK"
else :
    x = "NG"

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

python
x = "OK" if n == 10 else "NG"
253
181
5

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
253
181

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?