Menu
Coddy logo textTech

평균 성적

Coddy Python 여정의 Logic & Flow 섹션에 포함된 레슨 — 78개 중 43번째.

challenge icon

챌린지

쉬움

하나의 인자 name (문자열)을 받는 calculate_average_grade라는 이름의 함수를 만드세요. 이 함수는 다음을 수행해야 합니다:

  1. student_records 딕셔너리에 해당 학생 이름이 존재하는지 확인합니다.
    • 존재하지 않는 경우, "Student '<name>' not found."를 출력하고 None을 반환합니다.
  2. 이름이 존재하면, 학생의 grades 세트에 있는 성적의 평균을 계산합니다.
    • grades 세트가 비어 있으면 0을 반환합니다.
    • 그렇지 않으면, 평균 성적을 계산하여 float 타입으로 반환합니다.

코드의 맨 아래에 다음 코드 블록을 추가(교체)하세요:

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

Logic & Flow의 모든 레슨