Python成绩册程序读写记录与等级统计异常求助
Let's get your grade tracking program sorted out! I've put together a complete, working Python solution that handles all your requirements—inputting class/teacher/student info, counting grade distributions, and saving everything to a text file. Here's the code, followed by a breakdown of how each part works:
Working Grade Statistics Program
def main(): # Collect basic class information class_name = input("Enter the class name: ") teacher_name = input("Enter the teacher's name: ") # Set up counters for each grade level grade_counters = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0} student_grades = [] # Gather student data with input validation print("\nEnter student names and their letter grades (type 'done' when finished):") while True: student_name = input("Student name: ") if student_name.lower() == 'done': break # Ensure we get a valid letter grade grade = input(f"Letter grade for {student_name}: ").upper() while grade not in grade_counters: grade = input(f"Oops, that's not a valid grade! Please enter A/B/C/D/F for {student_name}: ").upper() student_grades.append((student_name, grade)) grade_counters[grade] += 1 # Compile all output content output_lines = [ f"Class Name: {class_name}", f"Teacher Name: {teacher_name}", "\nStudent Grades:", ] for name, grade in student_grades: output_lines.append(f"- {name}: {grade}") output_lines.append("\nGrade Distribution:") for grade, count in grade_counters.items(): output_lines.append(f"- {grade}: {count} student(s)") # Combine lines into a single string for easy printing/writing full_output = '\n'.join(output_lines) # Display results to the console print("\n" + full_output) # Save everything to the specified text file file_name = f"{class_name}Grades.txt" with open(file_name, 'w') as grade_file: grade_file.write(full_output) print(f"\nAll data has been saved to {file_name}") if __name__ == "__main__": main()
Key Features & Explanations
- Input Validation: The program checks that each grade is one of A/B/C/D/F, so you don't have to worry about invalid entries messing up your stats.
- Organized Data Tracking: We use a dictionary to count grades (super efficient for this kind of tallying) and a list to store individual student records.
- Dual Output: The same content is printed to the console and saved to a file, so you get immediate feedback and a permanent record.
- Clean File Handling: The
withstatement automatically closes the file after writing, which is the safest practice in Python to avoid data loss.
How to Use It
- Run the script.
- Enter the class name when prompted (e.g., "Math 101").
- Enter the teacher's name.
- For each student, type their name and their letter grade. When you're done adding students, type
doneas the student name. - The program will show you the full grade breakdown, and save all the info to a file named like
Math101Grades.txtin the same folder as the script.
内容的提问来源于stack exchange,提问作者Belewsmom
相关产品推荐
相关产品推荐

