<Python> if, else を1行で。

if,else構文を1行で収める方法。

式 if 条件あたり else 条件はずれ でいいらしい。

In [36]: a = 1

In [37]: b = 1

In [40]: def test():
   ....:     if a == 1:
   ....:         print('OK')
   ....:     else:
   ....:         print('NG')
   ....:

In [41]: test()
OK

In [42]: def test2():
   ....:     print('OK') if a == 1 else print('NG')
   ....:

In [43]: test2()
OK

In [44]: a = 2

In [45]: test()
NG

In [46]: test2()
NG

なるほど。。。 英文法だね。

stackoverflow stackoverflow.com