Menu
CoddyTech

È iscritto

Fa parte della sezione Logica e flusso del percorso GDScript di Coddy. Lezione 45 di 78.

challenge icon

Sfida

Facile

Verifica se uno studente frequenta un corso. Mantieni tutto ciò che hai scritto nei passaggi precedenti.

1. La funzione. Sotto le altre funzioni, scrivi is_enrolled(student_name: String, course: String) -> bool:

  • Se student_records non contiene il nome, stampa Student '<name>' not found. e restituisci false.
  • Altrimenti restituisci true quando il corso è nel set "courses" dello studente e false quando non lo è.

2. Il comando. Aggiungi un ramo per enrolled <name> <course>, ad esempio enrolled Alice Math, sopra ["show"]. Stampa il valore restituito da is_enrolled(). Per i comandi

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

l'output è:

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

Per uno studente non trovato, prima viene visualizzato il messaggio e dopo false.

Provalo tu

extends Node

# Ogni studente: name -> {"age": int, "grades": Array, "courses": un insieme di nomi di corsi}
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])

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore GDScript online