Menu
CoddyTech

Numeric for to range

Lesson 17 of 48 in Coddy's Python for Lua Developers course.

Lua numeric for loops include the end value when the step reaches it. Python range excludes its stop value. Python for iterates values directly; there is no need for Lua ipairs when the index is unused. Iterating a list binds each element object to the loop name. Reassigning an integer loop name does not replace a list slot, but mutating a nested mutable object affects that object. Build a new list or assign indexed elements when replacement is intended.

Lua example

for _, value in ipairs({2, 4}) do print(value) end
for i = 0, 3 do print(i) end

Python

for value in [2, 4]:
    print(value)
for i in range(3):
    print(i)

Porting trap

Python range(1, 3) visits one and two, unlike Lua for i = 1, 3, which also visits three.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Lua Developers

Practice on your own: Online Python compiler