Question
Answer and Explanation
To calculate the average of midterm and final scores using Python, you can follow these simple steps:
1. Input the Scores: First, you'll need to have the midterm and final scores. These can be directly assigned to variables or obtained from user input.
2. Calculate the Sum: Add the midterm and final scores together.
3. Calculate the Average: Divide the sum by 2 (since there are two scores).
4. Display the Result: Print or return the calculated average.
Here's a Python code snippet illustrating this process:
midterm_score = 75
final_score = 90
sum_of_scores = midterm_score + final_score
average_score = sum_of_scores / 2
print("The average score is:", average_score)
Alternatively, to take scores as input from a user:
midterm_score = float(input("Enter the midterm score: "))
final_score = float(input("Enter the final score: "))
sum_of_scores = midterm_score + final_score
average_score = sum_of_scores / 2
print("The average score is:", average_score)
Explanation:
- The code first defines two variables, `midterm_score` and `final_score`, which store the respective exam scores. - Then, `sum_of_scores` calculates the sum of these two scores. - `average_score` divides the sum by 2 to find the average. - Finally, the result is displayed using the `print` function.
Note that when taking input from the user, `float()` is used to convert the input string to a floating-point number, allowing for decimal scores.
This is a basic example but can be easily extended to handle more scores or be included in a larger program for grading calculations. Remember to handle cases like invalid inputs gracefully (e.g., by using try-except blocks if getting user input).