Menu
CoddyTech

for Loops Iterate Values

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

Accumulate results by visiting each value in a sequence, then use a bounded range when the sequence itself is a run of integers.

JavaScript

const sizes = [2, 5, 3];
let total = 0;
for (const size of sizes) {
  total += size;
}
console.log(total);

Python

sizes = [2, 5, 3]
total = 0
for size in sizes:
    total += size
print(total)

What changes

Both examples print 10. Python assigns each list element to the loop variable, much like JavaScript for...of. JavaScript for...in visits enumerable property names instead; translating it mechanically would change the meaning. The Python loop body is indented under a colon. Use range(stop) for integers starting at zero, or range(start, stop, step) to choose the start and step. The stop value is always excluded. A positive step needs a start below the stop to produce any values; a negative step moves downward. The step cannot be zero.

Common mistake

Do not add one to every range bound automatically. Decide whether the contract includes the upper endpoint first. Initialize an accumulator before the loop so an empty range still has a defined result, and print after the loop when only one total is required.

Your task

Sum an inclusive interval using a loop. The supplied input lines already convert the two endpoints to integers.

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 JavaScript Developers

Practice on your own: Online Python compiler