Menu
CoddyTech

Break

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 45 of 92.

The break statement stops a loop immediately. The program continues with the first statement after the loop.

for i in range(10):
	if i == 6:
		break
	print(i)
print("Done")

The loop prints the numbers until i is 6. Then the if condition is true, break runs, and the loop ends before print(i), so 6 is never printed:

0
1
2
3
4
5
Done

break is useful with while true:, a loop whose condition never becomes false. The loop runs until a break inside it stops it. This finds the first multiple of 7 that is greater than 50 and prints 56:

var n := 50
while true:
	n += 1
	if n % 7 == 0:
		break
print(n)
challenge icon

Challenge

Easy

The program prints the numbers from 1 to 10.

Add an if statement with break inside the loop, so the program prints only the numbers from 1 to 5, one per line. The loop must stop before printing 6.

Try it yourself

extends Node

func _ready():
	for i in range(1, 11):
		print(i)
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