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
trueMembership 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
trueA 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 westChallenge
EasyThe 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:
NAME is in the class.orNAME is not in the class., checkingnamesNAME has a grade.orNAME has no grade., checking the keys ofgradesSomeone scored GRADE.orNobody scored GRADE., checking the values ofgrades
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler