Menu
CoddyTech

Membership Checks

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

You already check membership with in and not in: "cat" in pets looks for an element of an array and "ell" in "hello" for text inside a string. Three more cases come up all the time.

On a dictionary, in checks the keys only. To look for a value, check the array returned by values():

var grades := {"Alice": 85, "Bob": 90}
print("Alice" in grades)
print(90 in grades)
print(90 in grades.values())
true
false
true

Membership also compares types. Text read with OS.read_string_from_stdin() is a string, and the string "90" is not the integer 90:

var scores := [70, 90]
print("90" in scores)
print(int("90") in scores)
false
true

A constant array of allowed values with in replaces a long chain of or, and it also works in a guard:

const DIRECTIONS = ["north", "south", "east", "west"]
var dir := "west"
match dir:
	var d when d in DIRECTIONS:
		print("Going ", d)
	_:
		print("You cannot go there")
Going west
challenge icon

Challenge

Easy

The program has an array names with the students of a class and a dictionary grades with the students who already have a grade. It reads a student name into student and a grade into grade (as text).

Print three lines:

  1. NAME is in the class. or NAME is not in the class., checking names
  2. NAME has a grade. or NAME has no grade., checking the keys of grades
  3. Someone scored GRADE. or Nobody scored GRADE., checking the values of grades

Replace NAME and GRADE with the input. For the inputs Dana and 85, the output is:

Dana is in the class.
Dana has no grade.
Someone scored 85.

Try it yourself

extends Node

func _ready():
	var names := ["Alice", "Bob", "Charlie", "Dana"]
	var grades := {"Alice": 85, "Bob": 90, "Charlie": 78}
	var student := OS.read_string_from_stdin()
	var grade := OS.read_string_from_stdin()
	# Print the three lines
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler