포함 여부 확인
Coddy GDScript 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 10번째.
이미 in과 not in으로 멤버십을 확인하고 있습니다. "cat" in pets는 배열의 요소를 찾고, "ell" in "hello"는 문자열 안의 텍스트를 찾습니다. 이 외에도 세 가지 경우가 자주 등장합니다.
딕셔너리에서는 in이 키만 확인합니다. 값을 찾으려면 values()가 반환하는 배열을 확인하세요:
var grades := {"Alice": 85, "Bob": 90}
print("Alice" in grades)
print(90 in grades)
print(90 in grades.values())true
false
true멤버십은 타입도 비교합니다. OS.read_string_from_stdin()으로 읽은 텍스트는 문자열이며, 문자열 "90"은 정수 90이 아닙니다:
var scores := [70, 90]
print("90" in scores)
print(int("90") in scores)false
truein을 사용한 허용 값의 상수 배열은 긴 or 연결을 대체하며, 가드에서도 작동합니다:
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챌린지
쉬움이 프로그램에는 한 반의 학생들이 들어 있는 배열 names와 성적이 이미 있는 학생들이 들어 있는 딕셔너리 grades가 있습니다. 학생 이름은 student에, 성적은 (텍스트로) grade에 읽어 들입니다.
세 줄을 출력하세요.
NAME is in the class.또는NAME is not in the class.를 출력하고,names를 확인합니다.NAME has a grade.또는NAME has no grade.를 출력하고,grades의 키를 확인합니다.Someone scored GRADE.또는Nobody scored GRADE.를 출력하고,grades의 값을 확인합니다.
NAME과 GRADE를 입력값으로 바꾸세요. 입력값이 Dana와 85일 때 출력은 다음과 같습니다.
Dana is in the class.
Dana has no grade.
Someone scored 85.직접 해보기
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()
# 세 줄을 출력하세요
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러