Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 位置引数とオプション引数の組み合わせ | 位置引数とオプション引数
Python関数チュートリアル

位置引数とオプション引数の組み合わせ

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

スマートフォンの合計費用を計算するために設計された関数を考える。この関数では、初期化時および関数呼び出し時にさまざまな属性を指定可能。

123456789101112131415161718192021222324
def 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 では、modelprice が必須の位置引数。

オプション(名前付き)引数

オプション引数は、位置または名前で渡すことができる。quantitydiscount はデフォルト値を持ち、名前付きパラメータで変更可能。

デフォルト値

オプション引数が省略された場合、デフォルト値が使用される。この例では、quantity1discount0 がデフォルト。

名前付きパラメータ

名前付きパラメータは、特に複数のオプション引数が存在する場合に値の割り当てを明確にする。

これらのルールにより、位置引数と名前付き引数を組み合わせることで、関数の柔軟性と可読性が向上する。

1. 関数における位置引数とオプション引数の組み合わせとは何ですか?

2. 位置引数の後にオプション引数を持つ関数はどのように定義しますか?

question mark

関数における位置引数とオプション引数の組み合わせとは何ですか?

正しい答えを選んでください

question mark

位置引数の後にオプション引数を持つ関数はどのように定義しますか?

正しい答えを選んでください

すべて明確でしたか?

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

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

セクション 2.  5

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 2.  5
some-alt