Loop Control Without ++
Lesson 19 of 48 in Coddy's Python for C++ Developers course.
Python while repeats while its condition tests true. break exits the nearest loop and continue skips the rest of the current iteration, as in C++. Increment with n += 1; Python has no increment operator. In a while loop, put the update where a continue cannot skip it indefinitely. A Python for loop advances its iterator automatically, so filtering with continue does not need a manual index update.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
int n = 0;
while (n < 3) {
++n;
if (n == 2) continue;
std::cout << n << '\n';
}Python
values = [2, -1, 0, 5]
total = 0
for value in values:
if value < 0:
continue
total += value
print(total)Porting trap
Python ++n is two unary plus operations, not an increment. It can run without changing n, making a direct port especially misleading.
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 one line at a time until the exact line stop, which is guaranteed to occur. Other lines are integers between -1000 and 1000. Ignore negative readings. Zero is valid. Print the count and sum of accepted readings on one line separated by a space. Ignore any input after stop.
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