A question about "for" and "range"

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dumuz

I was looking over the doc’s for using the for syntax and it was making sense until the example showed this line of script:

for i in range(2, 8, 2):
    statement # Similar to [2, 4, 6] but does not allocate an array.

Why does this generate these integers?
From the looks of these examples using for in range, it seems like it should iterate through the array as [2, 8, 2]. What math am I not understanding here?

:bust_in_silhouette: Reply From: jgodfrey

This answer was completely wrong - removed. :frowning:

When I put

for i in range(2, 8, 2):
     print(i)

in Godot, the debugger prints off 2, then 4, then 6.

Why doesn’t it print 2, than 8, than 2?

Dumuz | 2020-02-05 22:56

You can hide your answer by clicking the three vertical dots in the lower right corner of your reply and selecting “Hide”. From the standpoint of other users, this is the same as deleting your answer.

njamster | 2020-02-06 11:27

From how I understand Godot, that looks like the first argument in range() is the minimum value, followed by maximum value, and the 3rd argument simply means the incremental value, so how many steps you want to take from min_value to max_value

range(1,10, 2) would produce 1, 3, 5, 7, 9

cholasimmons | 2020-09-24 02:05

:bust_in_silhouette: Reply From: Magso

I can’t actually find an official doc for range but it takes minimum, maximum, in steps of x.

for i in range(3, 15, 3):
	print(i)
	#prints 3, 6, 9, 12

The best range docs I see are on this page. Just search for range:

GDScript: An introduction to dynamic languages — Godot Engine (3.2) documentation in English

jgodfrey | 2020-02-05 22:57

To be honest it doesn’t help that Range is on certain control nodes and range is a function that isn’t mentioned in the node documentation page.

Magso | 2020-02-05 23:05

I see, okay, I missed the part where range takes up to 3 arguments and when it’s does, the last variable is the increments. I appreciate the answer.

Dumuz | 2020-02-05 23:07

Thanks Jgodfrey

Dumuz | 2020-02-05 23:08

And just in case no one sees the description for the range function in the @GDscript documentation, here’s a link to it. :slight_smile:

Ertain | 2020-02-06 00:56

:bust_in_silhouette: Reply From: dacess123

Hey Dumuz, you should be reading this as:

for i in range(start_value, ending_value, step_size)

where step_size represents how much the i will increase by each iteration. So in the example provided, the for loop would go from 2 to 8 in increments of 2.

For comparison, when iterating through an array you would use:

for i in [2, 8, 2]:

Note the [] instead of the () used in the range iteration. This would then create the output you were expecting.