If Statement
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 26 of 92.
An if statement runs code only when a condition is true:
var hp := 25
var status := "Healthy"
if hp < 30:
status = "Hurt"
hp += 10GDScript checks hp < 30. It is true, so status becomes "Hurt". The last line is not indented, so it is outside the if and runs either way: hp becomes 35.
The rules of an if statement:
- The condition is followed by a colon
: - The code inside the
ifis indented one level deeper than theifline. Inside_ready(), that is two tabs - When the condition is
false, GDScript skips the indented lines
if condition:
print("Runs only when the condition is true")
print("Runs either way")The condition can be any expression that gives a bool, including logical operators: if hp > 0 and has_potion:. An if block cannot be empty: write pass in it when it has nothing to do yet.
Challenge
EasyChange the values of a and b so that the condition of the if statement is true and its block runs.
Do not change the lines below the comment. At the end, c must hold 3, so the output is:
c = 3There is more than one correct answer: try to find another one.
Try it yourself
extends Node
func _ready():
# Change the values of a and b
var a: int = 0
var b: int = 0
# Don't change the lines below
var c: int = 0
if a >= b and not b < 10:
c = 2
c += 1
print("c = ", c)
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