0
0

More than 1 year has passed since last update.

python で、代入式(walrus演算子、セイウチ演算子)を使おう!②(備忘録)

Last updated at Posted at 2022-12-05

python で、代入式(walrus演算子、セイウチ演算子)を使おう!①(備忘録)の続きです。

# 野菜ジュース屋台の在庫
vegetables = {
    'tomato': 15,
    'melon': 9,
    'goya': 5
}

事例②(代入式なし)

次にトマトジュースの注文が入りました。
トマトは5個使います。

def make_tomato_juice(count):
    pass

def out_of_stock():
    print('out_of_stock')
    
count = vegetables.get('tomato', 0)
if count >= 5:
    make_tomato_juice(count)
else:
    out_of_stock()

この場合も、if文の1行目だけで使うcountを無駄に強調してしまっています。

事例②(代入式あり)

def make_tomato_juice(count):
    pass

def out_of_stock():
    print('out_of_stock')

if (count := vegetables.get('tomato', 0)) >= 5:
    make_tomato_juice(count)
else:
    out_of_stock()

代入式を使うことによって、コードが1文短くなり、countの無駄な強調がなくなりました。
※if文で、countの代入式と5を比較するために、括弧でくくっています。

おまけ

walrus(ウォルラス)は、「:=」がセイウチの顔を横にして、目と牙に見立てているみたいです。

0
0
1

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
0