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
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler