사용자 정의 함수 정의하기

개발자를 위한 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 중급

사용자 정의 함수는 언제 필요할까

Don't Repeat Yourself(DRY)

$$

  • 사용자 지정 함수를 만들 때의 고려 사항:
    • 줄 수
    • 모델의 복잡성
    • 사용 빈도

사막

개발자를 위한 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...