single
ユーザー定義関数
メニューを表示するにはスワイプしてください
ユーザー定義関数は、特定のタスクを実行するために作成するコードのブロック。Pythonが提供する組み込み関数とは異なり、ユーザー定義関数はプログラム内の特定の問題を解決するために自分で記述するもの。定義後は何度でも再利用でき、コードの整理、効率化、保守性の向上に役立つ。
次に、Alexがユーザー定義関数の作成と利用方法を実演し、タスクの簡素化を示す例を見てみよう。
Pythonにおけるユーザー定義関数の基本構造は次のとおり:
def function_name(argument_1, argument_2):
# Code block
return result
def: 関数定義の開始を示すキーワード;function_name: 関数に付ける名前。関数の内容が分かるような説明的な名前にすることで、コードの可読性が向上する;argument_1, argument_2: 関数に渡す変数名。関数呼び出し時に値を受け取るためのプレースホルダー。パラメータは0個以上指定可能;- コロン
:は関数のコードブロックの開始を示す; # Code block: 関数本体。ここに関数が実行するコードを書く。ループや条件分岐と同様にインデントが必要;return: 関数の終了と結果の返却に使用する文。すべての関数で必須ではないが、値を呼び出し元に返したい場合に便利。
パラメータと引数
パラメータは、関数定義の括弧内に記載する変数。関数に渡される値(引数)を受け取るために使用する。
引数は、関数を呼び出す際に実際に渡す値。これらの値が関数のパラメータに割り当てられる。
1234def greet_customer(name): print(f"Hello, {name}! Welcome to our store.") greet_customer("Alice")
注意
上記の例では、
nameはパラメータであり、文字列"Alice"は引数です。
ボイド関数
上記のように、すべての関数が値を返す必要はありません。タスクを実行するだけで、呼び出し元に何も返さない関数もあります。これらはボイド関数と呼ばれます。
Pythonにおいて、ボイド関数とは、return 文が存在しない、または return 文が値を返さないユーザー定義関数です。どちらの場合も、関数はデフォルトで None を返します。
上記の例では、greet_customer() はボイド関数です。これは挨拶を出力する処理を行いますが、プログラム内で他の場所で保存したり利用したりできる結果を返しません。
ボイド関数の例
ここでは、return 文を使って関数の実行を終了させるものの、値は返さないボイド関数の別の例を示します。
123456789101112131415161718192021# Function to check stock levels of grocery items def check_stock(inventory): for item, stock in inventory.items(): if stock < 10: print(f"Warning: {item} is running low on stock with only {stock} units left!") print("Please restock the item before proceeding with the check.") return # Stops the function if stock is below 10 print(f"{item} has sufficient stock: {stock} units.") print("All items have sufficient stock.") # Example inventory of a grocery store inventory = { "Apples": 50, "Bananas": 30, "Milk": 8, # This will trigger the early exit "Bread": 25 } # Check stock levels check_stock(inventory)
実用例
ここでは、特定の値を返す関数について考えます。たとえば、店舗で異なる商品の割引額を計算する必要がある場合、割引計算を行う関数を作成できます。この関数は必要なときに何度でも再利用できます。
1234567891011121314# `cost` and `discount_rate` are the parameters of the function def calculate_discounted_price(cost, discount_rate): final_price = cost * (1 - discount_rate) return final_price # Call the `calculate_discounted_price` function and pass in `cost` and `discount_rate` values as arguments apples_final_price = calculate_discounted_price(1.2, 0.10) milk_final_price = calculate_discounted_price(2.2, 0.15) bread_final_price = calculate_discounted_price(0.8, 0.05) # Display the discounted prices print(f"The discounted price of apples is ${apples_final_price}") print(f"The discounted price of milk is ${milk_final_price}") print(f"The discounted price of bread is ${bread_final_price}")
スワイプしてコーディングを開始
商品の価格と販売数量を掛け合わせて、商品の合計コストを計算する関数の定義。
- 2つのパラメータ
calculate_total_cost()とpriceを受け取る関数quantityの作成。 - 関数内で、
priceとquantityを掛けて合計コストを算出。 - 関数からその結果を返却。
出力要件
calculate_total_cost()、price = 1.50でquantity = 10を呼び出す。- 結果を次の形式で出力:
The total cost for apples is $<apples_total_cost>
解答
フィードバックありがとうございます!
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください