カスタム関数の定義

開発者向け中級 Python

Jasmin Ludolf

Senior Data Science Content Developer

平均の計算

# List of preparation times (minutes)
preparation_times = [19.23, 15.67, 48.57, 23.45, 12.06, 34.56, 45.67]

# Calculating average preparation time average_time = sum(preparation_times) / len(preparation_times)
# Rounding the results rounded_average_time = round(average_time, 2) print(average_time)
28.46
開発者向け中級 Python

カスタム関数の作成タイミング

*DRY(Don't Repeat Yourself :繰り返さない)*

$$

  • カスタム関数を作成する際の考慮事項:
    • 行数
    • コードの複雑性
    • 使用頻度

砂漠

開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def








開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average








開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(








開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(values)








  • values (引数) - 関数がその役割を果たすために必要な情報
開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(values):








開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(values):
    # Calculate the average
    average_value = sum(values) / len(values)





開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(values):
    # Calculate the average
    average_value = sum(values) / len(values)

    # Round the results
    rounded_average = round(average_value, 2)



開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(values):
    # Calculate the average
    average_value = sum(values) / len(values)

    # Round the results
    rounded_average = round(average_value, 2)

# Return an output return
  • average_valuerounded_averageaverage()内でのみ利用可
開発者向け中級 Python

カスタム関数の作成

# Create a custom function to calculate the average value
def average(values):
    # Calculate the average
    average_value = sum(values) / len(values)

    # Round the results
    rounded_average = round(average_value, 2)

    # Return rounded_average as an output
    return rounded_average
  • ドキュメント化は重要 📚
開発者向け中級 Python

カスタム関数を使用する

# List of preparation times (minutes)
preparation_times = [19.23, 15.67, 48.57, 23.45, 12.06, 34.56, 45.67]

# Calculating the average print(average(preparation_times))
28.46
# List of orders
orders = [12, 8, 10, 9, 15, 21, 16]

print(average(orders))
12.86
開発者向け中級 Python

関数の出力を保存する

# Calculating the average
print(average(preparation_times))
28.46
# Storing average_time
average_time = average(preparation_times)

print(average_time)
28.46
開発者向け中級 Python

練習しましょう!

開発者向け中級 Python

Preparing Video For Download...