Python中如何将5个测试分数传入函数,输出对应等级并计算平均分
How to Pass Multiple Test Scores to a Python Function and Display Letter Grades
Hey there! Let's get this sorted out. Here's a straightforward way to create a function that takes 5 test scores, outputs each one's letter grade, and calculates the average.
Option 1: Using a List (Flexible for Any Number of Scores)
This approach uses a list to hold the scores, making it easy to adjust if you ever need more than 5 scores later:
def calculate_grades(scores): # Calculate and display the average average_score = sum(scores) / len(scores) print(f"Your test score average is: {average_score:.2f}") # Loop through each score to determine its letter grade for score in scores: if score >= 90: letter = "A" elif score >= 80: letter = "B" elif score >= 70: letter = "C" elif score >= 60: letter = "D" else: letter = "F" print(f"Score: {score} → Letter Grade: {letter}") # Get 5 test scores from the user with input validation user_scores = [] for num in range(1, 6): while True: try: score = float(input(f"Enter test score {num}: ")) if 0 <= score <= 100: user_scores.append(score) break else: print("Oops! Please enter a score between 0 and 100.") except ValueError: print("Invalid input! Please enter a numeric value.") # Call the function with the list of scores calculate_grades(user_scores)
Option 2: Passing 5 Individual Parameters
If you want to explicitly pass 5 separate scores to the function (as you mentioned in your question), this version works too:
def calculate_grades(score1, score2, score3, score4, score5): # Store scores in a list for easier processing scores = [score1, score2, score3, score4, score5] average_score = sum(scores) / 5 print(f"Your test score average is: {average_score:.2f}") # Determine and display each grade for score in scores: if score >= 90: letter = "A" elif score >= 80: letter = "B" elif score >= 70: letter = "C" elif score >= 60: letter = "D" else: letter = "F" print(f"Score: {score} → Letter Grade: {letter}") # Get user input for each score s1 = float(input("Enter test score 1: ")) s2 = float(input("Enter test score 2: ")) s3 = float(input("Enter test score 3: ")) s4 = float(input("Enter test score 4: ")) s5 = float(input("Enter test score 5: ")) # Call the function with individual scores calculate_grades(s1, s2, s3, s4, s5)
Quick Tips:
- Adjust the grade thresholds (like 90 for an A) if your class uses a different grading scale.
- The input validation in Option 1 prevents crashes from non-numeric inputs or impossible scores—always a nice touch for user-facing code!
- Both versions calculate the average by summing all scores and dividing by the total count.
内容的提问来源于stack exchange,提问作者Tommy Nixon
相关产品推荐
相关产品推荐

