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_falseFor example:
var age := 20
var status := "Adult" if age >= 18 else "Minor"
print(status) # AdultGDScript 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") # PassGive 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
EasyA 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"ifcoinsis greater than or equal toprice"Not enough coins"otherwise
The print() line outputs status. With the given values the output is:
Not enough coinsTry 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)
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