Menu
Coddy logo textTech

平均点の算出

CoddyのPythonジャーニー「Logic & Flow」セクションの一部 — レッスン 43/78。

challenge icon

チャレンジ

簡単

1つの引数 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のすべてのレッスン