Ranges and Rebinding
Lesson 17 of 48 in Coddy's Python for GDScript Developers course.
Both languages use for with iterables and half-open range endpoints. Python range returns a range object rather than a materialized list of all integers. A Python loop variable is a binding to each visited value; rebinding it does not replace a list slot. Mutating an element that is itself a list is different. Empty ranges are useful for boundary cases without special branches.
GDScript
extends SceneTree
func _init():
var values = [2, 4]
for value in values:
prints(value)
for n in range(3):
print(n)
quit()Python
values = [2, 4]
for value in values:
value += 1
print(*values)Porting trap
To replace integer list elements, assign by index or construct a new comprehension. Updating only the loop name does not rewrite the container.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
Challenge
BeginnerRead two integer lines, start then stop, each between -100 and 100. Print the sum of all integers from start through stop, inclusive. If start > stop, print 0. Print one integer and a newline. Keep the supplied input scaffold.
Your code goes in main.py. The locked driver.py starts your program and cannot be edited.
Try it yourself
# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module
run_module("main", run_name="__main__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler