LoginSignup
0
6

More than 5 years have passed since last update.

Pythonの三項演算子のネスト

Last updated at Posted at 2017-07-23

Pythonで三項演算子を書きたい時(備忘)

ex) 変数aが10以上の時、変数bはtrue、それ以外の時はfalseを代入したい

ternary_operator.py
b = true if a >= 10 else false

条件をもっと増やしたい時(備忘)

上記の場合は条件文が2つの場合に使えるが、条件がもっと増えた時にも三項演算子を使いたい場合はこうする

ex) 変数scoreが100の場合は'perfect'、60以上100未満の場合は'pass'、それ以外の場合は'fail'を出力したい

nested_ternary_operator.py
print('perfect' if score == 100 else 'pass' if score >= 60 and score < 100 else 'fail')

elseの式の後にifを加えることでif~elif~elseを表現できる
exの状況設定がガバガバなのはご愛嬌

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