请求Python实现CSV文件指定学生成绩行的平均值计算代码
Solution: Calculate a Student's Average Score from a CSV File
Got it, let's work through this problem together. The core task here is targeting a specific student's row (instead of columns) to compute their average score—something totally doable with Python's built-in tools.
Step-by-Step Breakdown
We'll use Python's csv module to safely parse the file, then:
- Grab user input for the filename and target student name
- Loop through each row to find the matching student
- Extract their scores, convert them to numbers, and calculate the average
- Add error handling for common issues like missing files or invalid data
Complete Working Code
import csv def get_student_average(): # Get user inputs filename = input("Enter the CSV filename (e.g., scores.csv): ") target_name = input("Enter the student's full name: ") try: # Open and read the CSV file with open(filename, mode='r') as file: csv_reader = csv.reader(file) # Iterate through each row to find the student for row in csv_reader: # Use strip() to handle accidental spaces in names if row[0].strip() == target_name.strip(): # Convert score strings to integers scores = [int(score) for score in row[1:]] # Calculate average average = sum(scores) / len(scores) print(f"\n{target_name}'s average score: {average:.2f}") return # If no matching student was found print(f"\nOops: Couldn't find '{target_name}' in {filename}") except FileNotFoundError: print(f"\nError: The file '{filename}' doesn't exist. Double-check the filename!") except ValueError: print("\nError: One or more scores aren't valid numbers. Check your CSV format.") except Exception as e: print(f"\nUnexpected error occurred: {e}") # Run the function get_student_average()
How This Works
- CSV Parsing: The
csv.readerturns each line into a list—where the first item is the student's name, and the rest are their scores. - Student Matching: We compare the first element of each row to the user's input (using
strip()to ignore extra spaces, like if someone types " Ms. Student " instead of "Ms. Student"). - Average Calculation: Once we find the right row, we convert all score values to integers, sum them, and divide by the number of scores to get the average.
- Error Handling: We catch common issues like missing files, non-numeric scores, or students not being in the file, so the program doesn't crash unexpectedly.
Test with Your Sample Data
If your CSV file (scores.csv) has this content:
Ms. Student,100,100,90,70,100 A Student,30,50,30,50,100 Mr. Student,80,85,70,100,90
Running the code and entering scores.csv + Mr. Student will output:
Mr. Student's average score: 85.00
内容的提问来源于stack exchange,提问作者Jon Dominguez
相关产品推荐
相关产品推荐

