Menu
CoddyTech

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 += 10

GDScript 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 if is indented one level deeper than the if line. 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 icon

Challenge

Easy

Change 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 = 3

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