Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C++ Developers

Practice on your own: Online Python compiler