Menu
CoddyTech

평균 성적

Coddy Python 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 43번째.

challenge icon

챌린지

쉬움

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

  1. 학생 이름이 student_records 딕셔너리에 있는지 확인합니다.
    • 없으면 "Student '<name>' not found."를 출력하고 None을 반환합니다.
  2. 이름이 있으면 학생의 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 컴파일러