Menu
CoddyTech

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

You can also write the conditions directly, without the extra variables:

var result := number > 0 and number % 2 == 0

With 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 # true

GDScript 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) # true

To 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 icon

Challenge

Easy

A player wants to explore a dungeon. The variables level, has_key and has_map are declared for you. Declare three more:

  • can_enter: level is at least 5 and the player has a key or a map
  • can_find_treasure: the player has a key and a map and level is at least 10
  • is_lost: the player has no key and no map, or level is below 3

Use and, or and not. With the given values, the output is:

Can enter: true
Can find treasure: false
Is lost: false

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