Menu
CoddyTech

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): from 0 up to end
  • range(start, end): from start up to end
  • range(start, end, step): from start up to end, moving by step each 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
9

A 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 icon

Challenge

Easy

The 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
9

The 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
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