We read your photo as:

Write a Python program to input 20 student scores and calculate total, average, highest, and lowest scores.

Computer Science

ScanSolve AI Answer

Here is a Python program that fulfills the requirements:

# Initialize an empty list to store student scores
scores = []
num_students = 20

print(f"Please enter {num_students} student scores.")

# Step 1: Input 20 student scores
for i in range(num_students):
    while True:
        try:
            score = int(input(f"Enter score for student {i + 1}: "))
            if 0 <= score <= 100:  # Assuming scores are between 0 and 100
                scores.append(score)
                break
            else:
                print("Score must be between 0 and 100. Please try again.")
        except ValueError:
            print("Invalid input. Please enter an integer score.")

# Step 2: Calculate Total, Average, Highest score, Lowest score
# Check if scores list is not empty to avoid errors
if scores:
    total_score = sum(scores)
    average_score = total_score / len(scores)
    highest_score = max(scores)
    lowest_score = min(scores)
else:
    total_score = 0
    average_score = 0
    highest_score = "N/A"
    lowest_score = "N/A"

# Step 3: Display the results
print("\n--- Student Score Analysis ---")
print(f"Total number of students: {num_students}")
print(f"All entered scores: {scores}")
print(f"Total score: {total_score}")
print(f"Average score: {average_score:.2f}") # Format to 2 decimal places
print(f"Highest score: {highest_score}")
print(f"Lowest score: {lowest_score}")

Explanation:

  1. Initialization: An empty list scores is created to store the input scores, and num_students is set to 20.
  2. Input Loop: A for loop iterates num_students times.
    • Inside the loop, input() prompts the user to enter each student's score.
    • A while True loop with a try-except block handles potential ValueError if the user enters non-integer input and ensures scores are within a valid range (0-100).
    • Valid scores are appended to the scores list.
  3. Calculations:
    • sum(scores) calculates the total score.
    • len(scores) gets the number of scores, which is used to calculate the average score.
    • max(scores) finds the highest score.
    • min(scores) finds the lowest score.
    • An if scores: check prevents errors if no scores were entered (though the loop ensures 20 scores are entered).
  4. Display Results: The calculated total, average, highest, and lowest scores are printed to the console using f-strings for clear formatting. The average score is formatted to two decimal places.
Was this helpful?

Still stuck on this one?

Ask a follow-up, and the answer starts from this question.

Got a different question?Ask your own question