Logical Operators Part 3
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 24 of 92.
You can combine several conditions in one expression. To check whether a number is positive and even:
var number := 6
var is_positive := number > 0
var is_even := number % 2 == 0
var result := is_positive and is_even # trueYou can also write the conditions directly, without the extra variables:
var result := number > 0 and number % 2 == 0With or, one true condition is enough. -4 is negative, so this is true even though -4 is not odd:
var number := -4
var negative_or_odd := number < 0 or number % 2 != 0 # trueGDScript evaluates not first, then and, then or. Parentheses change the order:
var level := 3
var has_key := false
var has_map := true
print(level >= 5 and (has_key or has_map)) # false
print(level >= 5 and has_key or has_map) # trueTo check that a value is in a range, write two comparisons joined by and: level >= 1 and level <= 10. GDScript reports the math form 1 <= level <= 10 as an error.
Challenge
EasyA player wants to explore a dungeon. The variables level, has_key and has_map are declared for you. Declare three more:
can_enter:levelis at least5and the player has a key or a mapcan_find_treasure: the player has a key and a map andlevelis at least10is_lost: the player has no key and no map, orlevelis below3
Use and, or and not. With the given values, the output is:
Can enter: true
Can find treasure: false
Is lost: falseTry it yourself
extends Node
func _ready():
var level := 7
var has_key := true
var has_map := false
# Declare can_enter, can_find_treasure and is_lost below
# Don't change the lines below
print("Can enter: ", can_enter)
print("Can find treasure: ", can_find_treasure)
print("Is lost: ", is_lost)
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