Menu
CoddyTech

Is Enrolled

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

challenge icon

Challenge

Easy

Check whether a student takes a course. Keep everything you wrote in the previous steps.

1. The function. Below the other functions, write is_enrolled(student_name: String, course: String) -> bool:

  • If student_records does not have the name, print Student '<name>' not found. and return false.
  • Otherwise return true when the course is in the student's "courses" set, and false when it is not.

2. The command. Add a branch for enrolled <name> <course>, such as enrolled Alice Math, above ["show"]. It prints the value that is_enrolled() returns. For the commands

add Alice 20 Math Physics
add Bob 22 Biology Chemistry
enrolled Alice Math
enrolled Alice Biology
enrolled Bob Biology
enrolled Charlie Math
exit

the output is:

Student 'Alice' added successfully.
Student 'Bob' added successfully.
true
false
true
Student 'Charlie' not found.
false
Goodbye!

For a student who is not found, the message comes first and false after it.

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))
			["grade", var student, var grade]:
				add_grade(student, int(grade))
			["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)

func add_grade(student_name: String, grade: int) -> void:
	if not student_records.has(student_name):
		print("Student '%s' not found." % student_name)
		return
	student_records[student_name]["grades"].append(grade)
	print("Grade %d added for student '%s'." % [grade, student_name])

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler