Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ ユーザー定義関数 | 関数
Python入門
セクション 6.  3
single

single

bookユーザー定義関数

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

ユーザー定義関数は、特定のタスクを実行するために作成するコードのブロック。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: 関数の終了結果の返却に使用する文。すべての関数で必須ではないが、値を呼び出し元に返したい場合に便利。

パラメータと引数

パラメータは、関数定義の括弧内に記載する変数。関数に渡される値(引数)を受け取るために使用する。

引数は、関数を呼び出す際に実際に渡す。これらの値が関数のパラメータに割り当てられる。

1234
def greet_customer(name): print(f"Hello, {name}! Welcome to our store.") greet_customer("Alice")
copy

注意

上記の例では、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)
copy

実用例

ここでは、特定の値を返す関数について考えます。たとえば、店舗で異なる商品の割引額を計算する必要がある場合、割引計算を行う関数を作成できます。この関数は必要なときに何度でも再利用できます。

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}")
copy
タスク

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

商品の価格販売数量を掛け合わせて、商品の合計コストを計算する関数の定義。

  • 2つのパラメータ calculate_total_cost()price を受け取る関数 quantity の作成。
  • 関数内で、pricequantity を掛けて合計コストを算出。
  • 関数からその結果を返却。

出力要件

  • calculate_total_cost()price = 1.50quantity = 10 を呼び出す。
  • 結果を次の形式で出力:
    The total cost for apples is $<apples_total_cost>

解答

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

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

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

セクション 6.  3
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt