If - Else
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 27 of 92.
else runs code when the if condition is false:
var age := 15
var status := ""
if age >= 18:
status = "Adult"
else:
status = "Young"age >= 18 is false, so the else block runs and status holds "Young".
To check more conditions in a row, use elif (short for "else if"):
var age := 68
var status := ""
if age < 18:
status = "Young"
elif age <= 65:
status = "Adult"
else:
status = "Senior"GDScript checks the conditions from top to bottom and runs only the first block whose condition is true. 68 fails both conditions here, so status holds "Senior".
You can add as many elif blocks as you need. else is optional and comes last. elif and else line up with their if, and the code inside them is indented one level deeper.
Challenge
EasyThe variable wind holds a wind speed, read for you on the first line (do not change that line). Use if, elif and else to set status:
"Calm"ifwindis less than8"Breeze"ifwindis from8to31(both included)"Gale"ifwindis from32to63(both included)"Storm"otherwise
Write all four cases: the tests try a different wind value each. For example, when wind is 45, the output is:
status = GaleTry it yourself
extends Node
func _ready():
var wind := int(OS.read_string_from_stdin()) # Don't change this line
var status := "unset"
# Write your if, elif and else code below
# Don't change the line below
print("status = ", status)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler