Conditional Statements (if/elif/else)
Hello and welcome to the GDScript fundamental tutorial series.
In this episode, I go over conditional statements (if/elif/else).
Definition
In programming, conditional statements are features of a programming language, which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.
In layman’s terms, sometimes programmers would like to do different code actions based on other decisions or results we get from code.
What types of conditional statements does GDScript have?
There are two different ways you can handle conditional statements in GDScript:
- if/elif/else statements
- match statements
The if keyword
Use the if
keyword to specify a block of code that runs if a condition is true:
if 2 > 1:
# run everything inside the block of code
If a condition is false, the block of code is skipped.
if 2 < 1:
# Block of code never runs
The else keyword
Use the else
keyword to run a block of code if the if statement condition is false:
if 2 < 1:
# Block of code never runs
else:
# Block of code runs
In this case, because the integer value 1 is never greater than 2, the else statement
will always run.
The elif keyword
Sometimes we want to test against multiple conditions before reaching an else keyword.
To do that, we use the elif
keyword.
The elif
keyword runs whenever the condition inside the if statement turns out false.
if 2 < 1:
# Block of code never runs
elif 2 > 1:
# Block of code runs
You are also able to chain multiple elif keywords together:
# An if statement chain
if 1 < 2:
# block of code
elif 1 < 3:
# block of code
elif 1 < 4:
# block of code
else:
# run code
Just keep in mind that you can only have one if
keyword and one else
keyword
in a single if statement chain.
Guess what happens here
var health: int = 100
if health >= 100:
print("Full Health")
elif health > 60:
print("Health is Good")
elif health > 30:
print("Health is low")
elif health >= 1:
print("Health is dangerously low")
else:
print("Health is depleted")