Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 関数の修正 | 関数
Python入門
セクション 6.  6
single

single

book関数の修正

メニューを表示するにはスワイプしてください

プログラミングにおいて、関数は動的なツールであり、さまざまな状況やニーズに適応可能です。関数は単なる固定されたコードのブロックではありません。関数を拡張することで、より柔軟で使いやすいものにすることができます。

この章では、デフォルト引数やキーワード引数の使用など、関数を修正するための重要なテクニックについて解説します。

まずは、関数の修正によって食料品店管理システムでの利便性を高めるシンプルな例から始めましょう。

デフォルト引数

デフォルト引数は、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}")
copy

キーワード引数

Pythonのキーワード引数は、各パラメータに明示的に名前を付けて引数を渡すことができ、関数呼び出しをより読みやすく柔軟にします。これは、関数に複数のパラメータがある場合や、引数の順序が混乱しやすい場合に特に役立ちます。

次の例では、pricediscountの両方が指定されており、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}")
copy

注意

キーワード引数を使って渡す場合、パラメータの順序は関係ありません

タスク

スワイプしてコーディングを開始

キーワード引数デフォルト値を活用し、割引税金を適用して商品の合計金額を計算する関数の作成。

  • 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>

注意

関数定義時は、必須パラメータを先に、デフォルト値付きパラメータを後に配置すること。

キーワード引数で関数を呼び出す際は、位置引数をキーワード引数より前に記述すること。

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 6.  6
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt