The Range Function
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 48 of 92.
range() can take one, two or three numbers:
range(end): from0up toendrange(start, end): fromstartup toendrange(start, end, step): fromstartup toend, moving bystepeach time
In all three, end is never included. The step is how much is added to get the next number. This prints the odd numbers below 10:
for i in range(1, 10, 2):
print(i)1
3
5
7
9A negative step counts backwards. The start must then be greater than the end. This counts down from 10 to 1:
for i in range(10, 0, -1):
print(i)The end is still not included, so the loop stops at 1. With range(20, 9, -2), the numbers are 20, 18, 16, 14, 12 and 10: 10 is included because it is still above 9.
If the start is already past the end, as in range(1, 5, -1), the range is empty and the loop does not run.
GDScript also lets you write a single number after in. for i in 3: works like for i in range(3):, with i going from 0 to 2.
Challenge
EasyThe program reads three whole numbers: start, end and step.
Use a for loop with range(start, end, step) to print every number of that range, one per line.
For the inputs 1, 10 and 2, the output is:
1
3
5
7
9The step can be negative: for 10, 0 and -3, print 10, 7, 4 and 1.
Try it yourself
extends Node
func _ready():
var start := int(OS.read_string_from_stdin())
var end := int(OS.read_string_from_stdin())
var step := int(OS.read_string_from_stdin())
# Write your for loop here
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