Menu
CoddyTech

for-in and range

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

Dart for-in and Python for both visit iterable elements. Python has no C-style three-part for statement; range supplies integer values when a counted loop is useful. Its stop is excluded and an empty interval performs no iterations. Rebinding a local loop variable holding an integer does not replace a list element in either language. Use indexed assignment or build a transformed list. Python loop targets remain bound in the surrounding scope after a nonempty loop, unlike a Dart loop-local declaration. An empty Python loop does not create a previously absent target binding.

Dart

void main() {
  final values = [2, 4];
  for (var value in values) {
    value += 1;
  }
  print(values);
  for (var i = 0; i < 2; i++) print(i);
}

Python

values = [2, 4]
for value in values:
    value += 1
print(values)
print(list(range(0, 2)))

Porting trap

Do not replace a counted loop with an inclusive Python stop. range excludes its endpoint.

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

Practice on your own: Online Python compiler