single
関数の修正
メニューを表示するにはスワイプしてください
プログラミングにおいて、関数は動的なツールであり、さまざまな状況やニーズに適応可能です。関数は単なる固定されたコードの塊ではありません。関数を拡張することで、より柔軟で使いやすくすることができます。
この章では、デフォルト引数やキーワード引数の利用など、関数を修正するための重要なテクニックについて解説します。
まずは、食料品店管理システムにおける関数の修正のシンプルな例から始めましょう。
デフォルト引数
デフォルト引数は、Pythonで関数パラメータにデフォルト値を指定できる便利な機能です。
apply_discount() 関数では、discount パラメータがデフォルトで 0.10 に設定されています。つまり、特に指定しない場合は10%割引が自動的に適用されます。default_discount_price 変数の例のように、price パラメータだけで関数を呼び出すことができます。
必要に応じて、price とカスタムの discount(例:20% の場合は 0.20)の両方を渡すことで、デフォルト値を上書きすることも可能です。これは custom_discount_price 変数の例で示されています。
123456789101112# Define a function with a default `discount` argument def apply_discount(price, discount=0.10): discounted_price = price * (1 - discount) return discounted_price # Call the function without providing a `discount`, using the default value default_discount_price = apply_discount(100) print(f"Price after applying the default discount: ${default_discount_price}") # Call the function with a custom `discount` value custom_discount_price = apply_discount(100, 0.20) print(f"Price after applying a custom discount: ${custom_discount_price}")
キーワード引数
Pythonのキーワード引数は、各パラメータに名前を付けて引数を渡すことができ、関数呼び出しをより読みやすく柔軟にします。特に、関数に複数のパラメータがある場合や、引数の順序が分かりにくい場合に役立ちます。
次の例では、priceとdiscountの両方が指定されており、taxパラメータはデフォルト値のままです。これにより、明確さを損なうことなく柔軟性が得られます。
12345678# Function where `tax` has a default value def calculate_total(price, discount, tax=0.05): total = price * (1 + tax) * (1 - discount) return total # Calling the function using keyword arguments total_cost = calculate_total(price=100, discount=0.15) print(f"Total cost after applying discount: ${total_cost}")
キーワード引数を使用してパラメータを渡す場合、パラメータの順序は関係ありません。
スワイプしてコーディングを開始
キーワード引数とデフォルト値を活用し、割引と税金を適用して商品の合計金額を計算する関数の作成。
apply_discount(price, discount=0.05)の定義
→ 割引適用後の価格を返す。apply_tax(price, tax=0.07)の定義
→ 税金加算後の価格を返す。calculate_total(price, discount=0.05, tax=0.07)の定義
→apply_discount()とapply_tax()を利用し、割引と税金を適用した合計金額を返す。- デフォルトの割引と税金で
calculate_total(120)を呼び出す。 - キーワード引数でカスタム値を指定し、
calculate_total(100, discount=0.10, tax=0.08)を呼び出す。
出力要件
- デフォルト値での結果を出力:
Total cost with default discount and tax: $<total_price_default> - カスタム値での結果を出力:
Total cost with custom discount and tax: $<total_price_custom>
解答
関数を定義する際は、必須パラメータを先に記述し、その後にデフォルト値を持つパラメータを配置。
キーワード引数を使用して関数を呼び出す場合、位置引数はキーワード引数より前に記述。
フィードバックありがとうございます!
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください