Menu
CoddyTech

Sentinels and Loop Control

Lesson 19 of 48 in Coddy's Python for C# Developers course.

Stop on a sentinel while retaining valid zero readings.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

int total = 0;
int[] values = { 2, -1, 4 };
foreach (int value in values) {
    if (value < 0) continue;
    total += value;
}
Console.WriteLine(total);

Python

total = 0
for value in [2, -1, 4]:
    if value < 0:
        continue
    total += value
print(total)

What changes

break exits the nearest loop; continue skips its remaining statements for the current iteration, as in C#. A Python while condition uses truth testing rather than requiring a bool expression, but explicit comparisons make numeric rules clear. For sentinel input, compare the raw text before converting it to an integer.

Transfer mistake

Zero is a valid reading in this task. Testing if not value would incorrectly discard zero. Never try int("stop").

Your task

Consume input lines until the exact text stop, which is guaranteed. Other lines are integers in [-1000, 1000]. Ignore negative readings but count zero. Output the count and sum of accepted readings separated by a space. Do not consume or process data after stop.

challenge icon

Challenge

Beginner

Consume input lines until the exact text stop, which is guaranteed. Other lines are integers in [-1000, 1000]. Ignore negative readings but count zero. Output the count and sum of accepted readings separated by a space. Do not consume or process data after stop.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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