Menu
CoddyTech

Điểm trung bình

Thuộc phần Logic và luồng chương trình trong hành trình Python của Coddy. Bài học 43 trên 78.

challenge icon

Thử thách

Dễ

Tạo một hàm (function) có tên calculate_average_grade, nhận một đối số: name (chuỗi). Hàm cần:

  1. Kiểm tra xem tên học sinh có trong từ điển student_records hay không.
    • Nếu không có, in ra "Student '<name>' not found." và trả về None.
  2. Nếu có tên đó, tính điểm trung bình từ tập hợp grades của học sinh.
    • Nếu tập hợp grades trống, trả về 0.
    • Nếu không, tính và trả về điểm trung bình dưới dạng số thực.

Thêm (thay thế bằng) khối code sau vào cuối code của bạn:

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

Tự làm thử

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

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch Python online