Nested If - Else
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 29 of 92.
An if statement can go inside another if or else block. This is a nested if. Start with a plain if/else:
var age := 15
var group := ""
if age >= 18:
group = "Adult"
else:
group = "Minor"Now split the minors in two with a nested if/else inside the else block:
var age := 15
var group := ""
if age >= 18:
group = "Adult"
else:
if age >= 13:
group = "Teenager"
else:
group = "Child"15 is not at least 18, so the outer else runs. Inside it, 15 >= 13 is true, so group holds "Teenager".
A nested if can also go inside the if block:
var age := 25
var can_rent_car := false
if age >= 18:
if age >= 21:
can_rent_car = trueThe inner if runs only when the outer block it sits in runs. Each level of nesting adds one tab.
Challenge
EasyDecide which movies a viewer can watch. The variables age and with_parent are read for you on the first two lines (do not change them).
Use a nested if/else to set message:
- If
ageis18or more:"You can watch any movie" - Otherwise, if
with_parentistrue:"You can watch PG-13 movies" - Otherwise:
"You can only watch G-rated movies"
with_parent is a bool, so check it directly: if with_parent:. Write all three cases: the tests try different ages with and without a parent. For example, for age 17 with a parent the output is:
You can watch PG-13 moviesTry it yourself
extends Node
func _ready():
var age := int(OS.read_string_from_stdin()) # Don't change this line
var with_parent := OS.read_string_from_stdin() == "true" # Don't change this line
var message := ""
# Write your nested if - else code below
# Don't change the line below
print(message)
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