Question
Answer and Explanation
To calculate the average midterm and final scores in Python, you can use basic arithmetic operations. Here's a step-by-step explanation with example code:
1. Store the Scores: You'll first need to store the midterm and final scores in variables. You can do this using integers or floating-point numbers, depending on whether the scores have decimal points.
2. Calculate the Averages: To calculate the average, sum the scores and divide by the number of scores. If there are multiple midterms, you'll need to sum all of them and divide by the count of midterms. The same logic applies to the final scores if there are multiple finals.
3. Handle Multiple Midterms or Finals: If there are more than one midterm or final scores, you can store them in a list and use the sum() function to calculate the sum of scores, then divide by the length of list to get average.
4. Example Code:
Here is how you can calculate the average using Python:
def calculate_average_scores(midterm_scores, final_scores):
"""Calculates the average of midterm and final scores.
Args:
midterm_scores (list or float): A list of midterm scores or a single midterm score.
final_scores (list or float): A list of final scores or a single final score.
Returns:
tuple: A tuple containing the average midterm score and the average final score.
"""
if isinstance(midterm_scores, list):
avg_midterm = sum(midterm_scores) / len(midterm_scores) if midterm_scores else 0
else:
avg_midterm = midterm_scores if midterm_scores is not None else 0
if isinstance(final_scores, list):
avg_final = sum(final_scores) / len(final_scores) if final_scores else 0
else:
avg_final = final_scores if final_scores is not None else 0
return avg_midterm, avg_final
# Example Usage:
midterm_scores_example = [75, 80, 85]
final_scores_example = [90, 95]
avg_mid, avg_final = calculate_average_scores(midterm_scores_example, final_scores_example)
print(f"Average Midterm Score: {avg_mid:.2f}")
print(f"Average Final Score: {avg_final:.2f}")
midterm_single = 80
final_single = 90
avg_mid, avg_final = calculate_average_scores(midterm_single, final_single)
print(f"Average Midterm Score: {avg_mid:.2f}")
print(f"Average Final Score: {avg_final:.2f}")
In this code, the `calculate_average_scores` function takes lists or single scores for midterms and finals. It checks if the inputs are lists; if so, calculates the average from the list; if not, it uses the given single score. The function will return the average scores of the midterms and finals. The example usage shows how to call this function and print the average score of midterms and finals.
This approach provides a flexible and clear way to handle both single and multiple scores while averaging them.