如何用字典与全局变量创建成绩册?代码排查及规范指导请求
Hey there! Let's break this down step by step—you're already on the right track using dictionaries and global variables for your gradebook, so let's clear up the confusion and fix your code issues.
Core Concepts to Start With
First, let's align on the basics to eliminate confusion:
- Global Variable: A variable defined outside any function that all functions can access. If you need to modify it inside a function, you must declare it with the
globalkeyword before any code that uses/modifies it. - Dictionary for Gradebook: Perfect for this use case! We can map assignment categories (like
'homework'or'midterm') to a pair of values: the total weighted score and total weight for that category. This makes calculating averages straightforward later.
Fixing Your Code Issues
Looking at your snippet, here are the key problems and fixes:
- Misplaced
globalDeclaration: Theglobal gradebookline needs to be at the top of your function. In Python, if you modify a global variable inside a function, you have to declare it global before any other code that interacts with it. Your current code checksweightfirst, which could lead to unexpected behavior. - Typo:
weigh...should beweight—you missed the last letter! - Uninitialized Categories: If the assignment type (like
'homework') isn't already in the gradebook, trying to accessgradebook[kind][0]will throw aKeyError. You need to add a new entry for unknown categories.
Corrected, Production-Ready Gradebook Example
Here's a polished version with proper naming, clear docstrings, and all essential functionality:
# Global gradebook dictionary: keys = assignment categories (str), values = [total_weighted_score, total_weight] gradebook = {} def add_assignment(assignment_type, grade, weight=1): """Add or update an assignment's grade in the gradebook. Args: assignment_type (str): Category of the assignment (e.g., 'homework', 'final_exam'). grade (float/int): Numeric grade received (0-100, or your scale). weight (float/int, optional): Relative weight of the assignment (defaults to 1). Returns: None """ global gradebook weighted_score = grade * weight if assignment_type in gradebook: # Update existing category: add to totals gradebook[assignment_type][0] += weighted_score gradebook[assignment_type][1] += weight else: # Initialize new category with this assignment's values gradebook[assignment_type] = [weighted_score, weight] def calculate_category_average(assignment_type): """Calculate the weighted average for a specific assignment category. Args: assignment_type (str): Category to compute the average for. Returns: float: Weighted average, or None if the category doesn't exist. """ if assignment_type not in gradebook: print(f"Error: No entries found for '{assignment_type}'") return None total_weighted_score, total_weight = gradebook[assignment_type] if total_weight == 0: print(f"Error: Total weight for '{assignment_type}' cannot be zero.") return None return total_weighted_score / total_weight def view_full_gradebook(): """Print the current gradebook with calculated averages for each category. Returns: None """ if not gradebook: print("Your gradebook is empty! Add some assignments first.") return print("=== Current Gradebook ===") for category, (total_weighted, total_weight) in gradebook.items(): avg = calculate_category_average(category) print(f"- {category}: Total Weighted Score = {total_weighted:.2f}, Total Weight = {total_weight:.2f}, Average = {avg:.2f}")
How to Test This Code
Let's walk through a quick example to see it in action:
# Add sample assignments add_assignment('homework', 92, 2) add_assignment('homework', 88, 2) add_assignment('midterm', 85, 3) add_assignment('final_exam', 90, 4) # View the complete gradebook view_full_gradebook() # Get average for homework print(f"\nHomework Average: {calculate_category_average('homework'):.2f}")
Sample Output:
=== Current Gradebook === - homework: Total Weighted Score = 360.00, Total Weight = 4.00, Average = 90.00 - midterm: Total Weighted Score = 255.00, Total Weight = 3.00, Average = 85.00 - final_exam: Total Weighted Score = 360.00, Total Weight = 4.00, Average = 90.00 Homework Average: 90.00
Key Best Practices to Remember
- Descriptive Naming: Use names like
assignment_typeinstead ofkind—this makes your code self-documenting and easier to debug later. - Docstrings: Every function has a clear docstring explaining its purpose, arguments, and return values. This is critical even for your future self!
- Global Variable Usage: Only use
globalin functions that modify the gradebook (likeadd_assignment). Functions that just read from it (likecalculate_category_average) don't need the declaration.
Once you're comfortable with this structure, you can extend it with features like removing assignments, resetting the gradebook, or calculating an overall course grade by combining category averages with their course weights.
内容的提问来源于stack exchange,提问作者Yungpythonnoob

