Menu
CoddyTech

Liệt kê theo khóa học

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 44 trên 78.

challenge icon

Thử thách

Dễ

Giữ lại mọi thứ bạn đã viết ở các bước trước của dự án này: toàn bộ tệp sẽ được chạy, vì vậy student_records và add_student vẫn phải có trong đó.

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

  1. Duyệt qua từ điển student_records và tìm tất cả học viên đăng ký khóa học course đã chỉ định.
  2. Trả về danh sách tên của những học viên đã đăng ký khóa học.
  3. Nếu không có học viên nào đăng ký khóa học, hãy trả về danh sách rỗng.

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, ["Math", "Biology"])
add_student("Diana", 23, ["Chemistry", "Physics"])
print(list_students_by_course("Math"))  # Should return ["Alice", "Bob"]
print(list_students_by_course("Physics"))  # Should return ["Alice", "Diana"]
print(list_students_by_course("Biology"))  # Should return ["Bob"]
print(list_students_by_course("History"))  # Should return an empty list

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"]

def calculate_average_grade(name):
    if name not in student_records:
        print(f"Student '{name}' not found.")
        return None
    grades = student_records[name]["grades"]
    if not grades:
        return 0
    return sum(grades) / len(grades)


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ấ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