Range Loops and Rebinding
Lesson 17 of 48 in Coddy's Python for C++ Developers course.
Python for visits values from an iterable. range(start, stop, step) supplies integers and excludes stop; range(3) visits 0, 1, 2. There is no three-clause C++ for syntax. C++ auto& in a range loop can refer to a container element, so assignment updates that element. Python for value in values binds a name to each object; rebinding value does not replace a list slot. Mutating an element that is itself mutable is a different operation.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
std::vector<int> values{2, 4};
for (auto& value : values) value += 1;
std::cout << values[0] << ' ' << values[1] << '\n';Python
for value in [2, 4]:
print(value)
for i in range(3):
print(i)Porting trap
For integer elements, use indexed assignment or build a new list to change every value. value += 1 in a Python loop rebinds the local name.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and 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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler