Menu
CoddyTech

Ternary Operator

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 25 of 92.

The ternary operator picks one of two values based on a condition. It has three parts:

value_if_true if condition else value_if_false

For example:

var age := 20
var status := "Adult" if age >= 18 else "Minor"
print(status) # Adult

GDScript checks age >= 18. It is true, so status gets "Adult". If age were 15, status would get "Minor".

The values can be numbers or variables, and the result can go straight into print():

var x := 10
var y := 20
var bigger := x if x > y else y # 20
print("Pass" if 75 >= 60 else "Fail") # Pass

Give both values the same type. var r := 1 if ok else "one" is an error, because GDScript cannot tell whether r is an int or a String.

The condition can use logical operators: "Open" if has_key and level >= 5 else "Locked".

challenge icon

Challenge

Easy

A player has coins and wants to buy an item that costs price. Both variables are declared for you.

Declare a variable status with the ternary operator:

  • "Purchase complete" if coins is greater than or equal to price
  • "Not enough coins" otherwise

The print() line outputs status. With the given values the output is:

Not enough coins

Try it yourself

extends Node

func _ready():
	var coins := 150
	var price := 200
	# Declare status with the ternary operator below

	# Don't change the line below
	print(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