平均成绩
本课属于 Coddy Python 学习旅程的“逻辑与流程”单元。第 43 课,共 78 课。
挑战
简单创建一个名为 calculate_average_grade 的函数,它接受一个参数:name(字符串)。函数应执行以下操作:
- 检查学生姓名是否存在于
student_records字典中。- 如果不存在,则打印
"Student '<name>' not found."并返回None。
- 如果不存在,则打印
- 如果姓名存在,则计算该学生
grades集合中成绩的平均值。- 如果
grades集合为空,则返回0。 - 否则,计算平均成绩并以浮点数形式返回。
- 如果
在代码底部添加(替换为)以下代码块:
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
print(calculate_average_grade("Alice")) # Should return 87.5
print(calculate_average_grade("Bob")) # Should return 75.0
print(calculate_average_grade("Charlie")) # Non-existent student, should print message and return None
print(calculate_average_grade("Alice")) # Should return 87.5 again亲手试试
student_records = {}
def add_student(name, age, courses):
if name in student_records:
print(f"Student '{name}' already exists.")
return
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
def add_grade(name, grade):
if name not in student_records:
print(f"Student '{name}' not found.")
return
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
def is_enrolled(name, course):
if name not in student_records:
print(f"Student '{name}' not found.")
return False
return course in student_records[name]["courses"]
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Charlie", 80) # Non-existent student
print(is_enrolled("Alice", "Math")) # Should return True
print(is_enrolled("Alice", "Biology")) # Should return False
print(is_enrolled("Bob", "Biology")) # Should return True
print(is_enrolled("Charlie", "Math")) # Non-existent student, should print message and return False逻辑与流程中的所有课
自己练习: Python 在线编译器