Menu
CoddyTech

Add Grade

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 44 of 78.

challenge icon

Challenge

Easy

Record the grades of the students. Keep everything you wrote in the previous steps.

1. The function. Below the other functions, write add_grade(student_name: String, grade: int) -> void:

  • If student_records does not have the name, print Student '<name>' not found. and return.
  • Otherwise append the grade to the student's "grades" array and print Grade <grade> added for student '<name>'.

The grades are an array, not a set, because a student can get the same grade twice and both count.

2. The command. Add a branch for grade <name> <grade>, such as grade Alice 90, above ["show"]. It calls add_grade() with the grade converted to an int. For the commands

add Alice 20 Math Physics
add Bob 22 Biology Chemistry
grade Alice 90
grade Alice 85
grade Bob 75
grade Charlie 80
show
exit

the output is:

Student 'Alice' added successfully.
Student 'Bob' added successfully.
Grade 90 added for student 'Alice'.
Grade 85 added for student 'Alice'.
Grade 75 added for student 'Bob'.
Student 'Charlie' not found.
{ "Alice": { "age": 20, "grades": [90, 85], "courses": { "Math": true, "Physics": true } }, "Bob": { "age": 22, "grades": [75], "courses": { "Biology": true, "Chemistry": true } } }
Goodbye!

Try it yourself

extends Node

# Every student: name -> {"age": int, "grades": Array, "courses": a set of course names}
var student_records := {}

func _ready():
	while true:
		var parts := Array(OS.read_string_from_stdin().split(" ", false))
		match parts:
			["add", var student, var age, ..]:
				add_student(student, int(age), parts.slice(3))
			["show"]:
				print(student_records)
			["exit"]:
				print("Goodbye!")
				break

func add_student(student_name: String, age: int, courses: Array) -> void:
	if student_records.has(student_name):
		print("Student '%s' already exists." % student_name)
		return
	var course_set := {}
	for course in courses:
		course_set[course] = true
	student_records[student_name] = {"age": age, "grades": [], "courses": course_set}
	print("Student '%s' added successfully." % student_name)

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler