You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用字典与全局变量创建成绩册?代码排查及规范指导请求

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.

Gradebook with Dictionary & Global Variables: A Practical Guide

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 global keyword 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:

  1. Misplaced global Declaration: The global gradebook line 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 checks weight first, which could lead to unexpected behavior.
  2. Typo: weigh... should be weight—you missed the last letter!
  3. Uninitialized Categories: If the assignment type (like 'homework') isn't already in the gradebook, trying to access gradebook[kind][0] will throw a KeyError. 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_type instead of kind—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 global in functions that modify the gradebook (like add_assignment). Functions that just read from it (like calculate_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:14:13