Menu
CoddyTech

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 icon

Challenge

Easy

The 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" if wind is less than 8
  • "Breeze" if wind is from 8 to 31 (both included)
  • "Gale" if wind is from 32 to 63 (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 = Gale

Try 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)
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