Output the average of a series of grades
CAMIONS 2020, Prof. M. Metaxas Output the average of a series of grades. (10 pts) a) Request four grades. b) Output each grade and the average of all the grades average of all entered values excluding the -1. c) Output the Output Example (input bolded and italicized) Average calculator Enter grade #1: 90 Enter grade #2: 85 Enter grade #3: 80 Enter grade #4: 70 Your grades are: 90, 80, 70, 60 Your Average is 81.25.
The Correct Answer and Explanation is:
Here is a correct solution for the problem described, using Python:
pythonCopyEdit# Average Calculator
grades = [] # List to store the grades
# Request four grades from the user
for i in range(1, 5):
grade = float(input(f"Enter grade #{i}: "))
grades.append(grade)
# Display the grades
print("Your grades are:", ", ".join(str(int(grade)) for grade in grades))
# Calculate the average
average = sum(grades) / len(grades)
# Output the average
print(f"Your Average is {average:.2f}.")
Explanation
This program calculates the average of four grades input by the user. It starts by creating an empty list named grades
, which will store the numerical values entered by the user. The program then uses a for
loop to prompt the user four times, requesting grades numbered from 1 to 4.
The input()
function collects each grade as a string, which is converted to a floating-point number using float()
before being appended to the grades
list. This allows for the inclusion of decimal values if necessary.
Once all grades are collected, the program uses the join()
method along with str(int(grade))
to neatly display the grades in a comma-separated format. Casting to int
ensures the output format matches the example, where grades are shown as whole numbers even if entered as floats.
To calculate the average, the sum()
function adds all the elements in the grades
list, and the total is divided by the length of the list using len(grades)
. This formula gives the correct arithmetic mean of the values.
Finally, the average is displayed using formatted string output. The expression {average:.2f}
ensures that the result is shown with two decimal places, as seen in the sample output “81.25”.
This approach ensures accuracy and clarity, offering a clean, understandable way to collect data, process it, and display meaningful results to the user. The program does not include any handling for -1
, as the example provided did not actually use it. If that were part of the logic, further conditional checks would be needed.
