For Loop
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 43 of 92.
A loop runs the same block of code several times. Instead of writing the same print() five times, you write it once inside a loop.
The for loop runs its block once for every number in a range. range(start, end) gives the numbers from start up to end, not including end:
for i in range(0, 5):
print(i)0
1
2
3
4Each run of the block is an iteration. On every iteration, the loop variable i holds the next number of the range. The for line ends with a colon, and the lines that repeat are indented one level deeper.
When the range starts at 0, you can leave the start out: range(5) gives the same numbers as range(0, 5).
Inside the block, i works like any other variable:
for i in range(1, 4):
print("Item number: ", i)Item number: 1
Item number: 2
Item number: 3A loop can also build up a result. This program adds up all the numbers from 1 to 100 and prints 5050:
var total := 0
for i in range(1, 101):
total += i
print(total)The last print() is not indented under the for line, so it runs once, after the loop has finished.
Challenge
EasyUse a for loop to print Hello Coddy: followed by each number from 3 to 27 (both included).
That is 25 lines in total:
Hello Coddy: 3
Hello Coddy: 4
...
Hello Coddy: 27Try it yourself
extends Node
func _ready():
# Write your for loop here
pass
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