Python成绩统计程序函数调用与循环终止问题求助
Hey Justin, let's break down the issues with your code and fix them step by step. I'll walk through the problems, explain why they're happening, and share a revised version of your program that works as intended.
Key Issues in Your Original Code
- Variable Scope Problems
- Variables like
s_pass,s_fail, andaverage_gradeare defined inside functions (local variables), so they can't be accessed outside those functions. The print statements at the bottom can't see these values at all.
- Variables like
- Broken Function Flow
- While your call chain (
collect()→average()→calculate()→passer()) runs, none of these functions return data to the main code. All the calculated values get trapped inside the functions.
- While your call chain (
- Type Errors in Printing
- You can't directly concatenate strings with integers or lists (e.g.,
print("Number of students that failed: " + s_fail)will throw an error becauses_failis an integer).
- You can't directly concatenate strings with integers or lists (e.g.,
- Edge Case Oversights
- If no scores are entered before typing "done", your code will crash when trying to calculate the average (division by zero).
Fixed & Improved Code
Here's a revised version that addresses all these issues, with clearer function responsibilities and proper flow:
# Initialize global lists to store raw scores and letter grades student_scores = [] letter_grades = [] def collect_scores(): while True: user_input = input("Enter student's score (or type 'done' to finish): ") # Terminate loop when user enters "done" (case-insensitive) if user_input.lower() == "done": # Trigger all processing steps once input is complete class_average = calculate_average(student_scores) assign_letter_grades(student_scores) pass_fail_counts = count_pass_fail(letter_grades) print_all_results(class_average, pass_fail_counts, student_scores, letter_grades) break # Validate input is a numeric value try: score = float(user_input) student_scores.append(score) except ValueError: print("Oops, that's not a valid number. Please try again.") def calculate_average(scores): # Handle empty list to avoid division by zero if not scores: return 0.0 return sum(scores) / len(scores) def assign_letter_grades(scores): # Clear existing grades to avoid duplicates if function runs multiple times letter_grades.clear() for score in scores: if score >= 80: letter_grades.append("A") elif score >= 70: letter_grades.append("B") elif score >= 60: letter_grades.append("C") elif score >= 50: letter_grades.append("D") else: letter_grades.append("F") def count_pass_fail(grades): failed = 0 passed = 0 for grade in grades: if grade == "F": failed += 1 else: passed += 1 # Return counts as a tuple for easy unpacking return (passed, failed) def print_all_results(average, pass_fail, scores, grades): passed, failed = pass_fail # Use f-strings for clean, type-safe printing print(f"\n=== Class Results ===") print(f"Number of students that failed: {failed}") print(f"Number of students that passed: {passed}") print(f"Raw scores: {scores}") print(f"Letter grades: {grades}") print(f"Average class grade: {round(average, 2)}") # Round to 2 decimal places for readability # Start the program collect_scores()
What Changed & Why
- Clearer Function Flow:
collect_scores()handles input, then calls all processing functions in sequence, finally passing all results toprint_all_results()to display everything. Each function has a single, clear job. - Variable Scope Fix: Instead of trapping values inside functions, we return calculated data (like the average and pass/fail counts) and pass them where needed. This avoids over-reliance on global variables.
- Proper Loop Termination: The loop breaks cleanly when "done" is entered, and immediately triggers all post-input processing. We also added case-insensitive checking so "Done" or "DONE" works too.
- Input Validation: The
try/exceptblock ensures only valid numbers are added to the score list, preventing crashes from bad input. - Type-Safe Printing: F-strings automatically convert non-string values (integers, floats, lists) to strings, eliminating concatenation errors.
内容的提问来源于stack exchange,提问作者Justin Kim
相关产品推荐
相关产品推荐

