位置引数とキーワード可変長引数の組み合わせ
メニューを表示するにはスワイプしてください
複数の商品の合計金額を計算し、任意の数の価格と、割引や税金などのオプションのキーワード設定を渡すことができる関数の例。
12345678910111213141516171819202122232425def calculate_total_cost(*prices, **settings): subtotal = sum(prices) discount = settings.get("discount", 0) tax = settings.get("tax", 0) discount_amount = subtotal * (discount / 100) taxed_amount = (subtotal - discount_amount) * (1 + tax / 100) print(f"Subtotal: ${subtotal:.2f}") if discount > 0: print(f"Discount: {discount}% (-${discount_amount:.2f})") else: print("No discount applied.") if tax > 0: print(f"Tax: {tax}% (+${taxed_amount - (subtotal - discount_amount):.2f})") print(f"Final total: ${taxed_amount:.2f}") print() # Examples of using the function calculate_total_cost(1000, 250, 50) calculate_total_cost(1200, 800, discount=10) calculate_total_cost(500, 750, 250, discount=5, tax=8)
可変長引数の組み合わせに関するルール
位置引数の可変長引数(*args)
*args は、すべての追加の位置引数をタプルとしてまとめる。
この例では、関数は明示的に定義することなく任意の数の商品の価格を受け取ることができる。
例:
calculate_total_cost(500, 250, 100)
ここで、*prices は (500, 250, 100) となる。
キーワード可変長引数(**kwargs)
**kwargs は、すべての名前付き(キーワード)引数を辞書としてまとめる。
これにより、関数は discount や tax など、事前に定義されていない追加の名前付き設定も受け付けることができる。
例:
calculate_total_cost(1000, 500, discount=10, tax=5)
この場合、**settings は {'discount': 10, 'tax': 5} となる。
両方の組み合わせ
*args と **kwargs の両方を同じ関数で使うことで、最大限の柔軟性を実現できる。任意の数の位置引数と、任意の組み合わせの名前付き設定を扱うことが可能。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 3
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 3