7.5 Code Practice
Use the function written in the last lesson to calculate the gold medalists average award money for all of their gold medals. Define another function in your program to calculate the average.
Your program should then output the average award money, including the decimal place. Your program should use a total of two functions. You may assume that the user will provide valid inputs.
The correct answer and explanation is:
Here’s the solution, followed by a detailed explanation.
Code:
# Function to calculate total award money for gold medals
def calculate_total_award_money(award_money_list):
return sum(award_money_list)
# Function to calculate the average award money per gold medal
def calculate_average_award_money(award_money_list):
total_award_money = calculate_total_award_money(award_money_list)
average_award_money = total_award_money / len(award_money_list)
return average_award_money
# Input: list of award money for gold medals
award_money_list = [5000, 7000, 8000, 10000] # Example input
# Calculate and display the average award money
average_award_money = calculate_average_award_money(award_money_list)
print(f"The average award money per gold medal is: {average_award_money:.2f}")
Explanation (300 Words):
This program is designed to calculate the average award money received for all gold medals by an athlete or team. It uses two functions to achieve modularity and clarity:
1. calculate_total_award_money:
This function takes a list of award amounts (e.g., [5000, 7000, 8000, 10000]) and calculates the total sum. It uses Python’s built-in sum() function for simplicity. The primary role of this function is to encapsulate the logic of summing the list values, making it reusable and easy to debug.
2. calculate_average_award_money:
This function calculates the average award money. It first calls calculate_total_award_money to get the total sum of all award amounts. It then divides this sum by the number of gold medals (i.e., the length of the list, retrieved using len()). This division produces the average award money.
Program Workflow:
- The list of award amounts (
award_money_list) is provided as input. In the example, the input[5000, 7000, 8000, 10000]represents the award amounts for four gold medals. - The
calculate_total_award_moneyfunction computes the total award money, which is 5000+7000+8000+10000=300005000 + 7000 + 8000 + 10000 = 30000. - The
calculate_average_award_moneyfunction divides this total (3000030000) by the number of gold medals (44) to compute the average (7500.007500.00). - Finally, the program formats the average to two decimal places using the
:.2fformat specifier and displays it.
This approach demonstrates good programming practices by separating concerns into distinct functions, making the code easy to understand, maintain, and reuse.