位置引数とオプション引数の組み合わせ
メニューを表示するにはスワイプしてください
スマートフォンの合計費用を計算するために設計された関数を考える。初期化時および関数呼び出し時にさまざまな属性を指定可能。
123456789101112131415161718192021222324def calculate_smartphone_cost(model, price, quantity=1, discount=0): total_cost = price * quantity discount_amount = total_cost * (discount / 100) discounted_cost = total_cost - discount_amount print(f"Model: {model}") print(f"Unit price: ${price}") print(f"Quantity: {quantity}") print(f"Total cost before discount: ${total_cost}") if discount > 0: print(f"Discount: {discount}%") print(f"Discount amount: ${discount_amount}") print(f"Discounted cost: ${discounted_cost}") else: print("No discount applied.") print(f"Final cost: ${discounted_cost}") print() # Examples of using the function calculate_smartphone_cost("iPhone 13", 1099, 2) calculate_smartphone_cost("Samsung Galaxy S21", 999, 1, 10) calculate_smartphone_cost("Google Pixel 6", 799, quantity=3, discount=5)
引数指定のルール
位置引数
位置引数は関数定義内の順序に従う必要がある。calculate_smartphone_cost では、model と price が必須の位置引数。
オプション(名前付き)引数
オプション引数は、位置または名前で渡すことができる。quantity と discount はデフォルト値を持ち、名前付きパラメータで変更可能。
デフォルト値
オプション引数が省略された場合、デフォルト値が使用される。例では、quantity は 1、discount は 0 がデフォルト。
名前付きパラメータ
名前付きパラメータは、特に複数のオプション引数がある場合に値の割り当てを明確にする。
これらのルールにより、位置引数と名前付き引数を組み合わせることで、関数の柔軟性と可読性が向上する。
1. 関数における位置引数とオプション引数の組み合わせとは何ですか?
2. 位置引数の後にオプション引数を持つ関数はどのように定義しますか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 5
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 2. 章 5