Menu
CoddyTech

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 = true

The inner if runs only when the outer block it sits in runs. Each level of nesting adds one tab.

challenge icon

Challenge

Easy

Decide 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 age is 18 or more: "You can watch any movie"
  • Otherwise, if with_parent is true: "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 movies

Try 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)
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online GDScript compiler