Skip to reading
GDScript Programming & Godot

8. If, elif, else and conditional expressions

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page
Code example
func describe_charge(charge: float) -> String:
    if charge >= 80.0:
        return "Fully charged."
    elif charge >= 30.0:
        return "Enough for one attempt."
    else:
        return "The battery is flat."
Code example
func run() -> String:
    return describe_charge(45.0)

The first true branch runs. Place specific conditions before broad ones. A return can end a function early, which is useful for rejecting an impossible interaction before starting the successful sequence.

Code example
func run() -> String:
    var opened: bool = true
    return "Open" if opened else "Locked"

A conditional expression chooses one value. Keep it short; use normal branches when a choice needs several actions or a useful explanation to the player.

Page 16 of 378Permalink
Go to page