Menu

GDScript if, elif, else and the Ternary Operator

Make decisions in GDScript with if, elif and else, combine conditions with and, or and not, test membership with in, and write one-line choices with the ternary form.

This page includes runnable editors. Edit, run, and see output instantly.

if runs a block only when its condition is true. elif adds more conditions, and else catches everything left:

100: healthy
50: hurt
10: critical
0: defeated

Godot tests the conditions from the top and runs the first one that is true. The rest are skipped, so the order matters: check hp > 70 before hp > 30.

Comparison and Logic Operators

OperatorMeaning
==, !=equal, not equal
<, >, <=, >=less, greater, or equal
and (or &&)both are true
or (or ||)at least one is true
not (or !)the opposite
inis in the array, dictionary or string
The door opens
Ranged attack
The word has an o

and and or stop early. In target != null and target.hp > 0, the second part only runs when target is not null, so this is a safe way to guard an access.

Truthy and Falsy Values

A condition does not have to be a bool. These values count as false: 0, 0.0, "", [], {}, null and zero vectors. Everything else counts as true:

Inventory is empty
Hello, Ana

The Ternary Form

For a choice between two values, write it on one line: a if condition else b.

defeated
1 coin

It is an expression, so it goes wherever a value goes: a variable, an argument, a return. Keep it for short choices. Nested ternaries are legal but hard to read; use if or match instead.

Nesting and Early Returns

Deep nesting makes game logic hard to follow. A common Godot pattern is to return early when a condition fails:

func _physics_process(delta):
	if not is_on_floor():
		velocity.y += gravity * delta
		return
	if Input.is_action_just_pressed("jump"):
		velocity.y = -jump_speed

Each if handles one case and leaves, so the code below it can assume the case did not happen.

An Empty Block

GDScript does not allow an empty block. Use pass as a placeholder while you write the rest:

if enemy_in_range:
	pass  # attack logic goes here later

Frequently Asked Questions

How do I write else if in GDScript?

Use elif: if hp > 50:, then elif hp > 0:, then else:. Godot checks the conditions in order and runs only the first block whose condition is true.

Does GDScript have a ternary operator?

Yes, written the Python way: var label = "alive" if hp > 0 else "dead". The value before if is used when the condition is true, the value after else when it is false. There is no ?: form.

Can I use && and || in GDScript?

Yes. &&, || and ! work, and so do the words and, or and not. The official style guide prefers the words.

What counts as false in a GDScript if?

false, 0, 0.0, an empty string, an empty array, an empty dictionary, null and a zero vector such as Vector2.ZERO. Everything else counts as true.

Coddy programming languages illustration

Learn to code with Coddy

Get started