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
Donebreak 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
EasyThe 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)
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