Menu
CoddyTech

Sentinels and Loop Control

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

C and Python break exit the nearest loop, while continue skips to its next iteration. Python while repeats while its condition tests true; while True with an explicit break is useful when the sentinel arrives inside the loop. Compare the input text with the sentinel before integer conversion. A zero measurement is still data, so testing if not reading would conflate it with missing information. The task counts accepted zero readings even though they add nothing to the sum.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    int readings[] = {2, -1, 0, 99}; int sum = 0;
    for (int i = 0; i < 4; ++i) {
        if (readings[i] == 99) break;
        if (readings[i] < 0) continue;
        sum += readings[i];
    }
    printf("%d\n", sum);
    return 0;
}

Python: complete example.py

total = 0
for reading in [2, -1, 0, 99]:
    if reading == 99:
        break
    if reading < 0:
        continue
    total += reading
print(total)

Watch the difference

C input APIs commonly report EOF as a status distinct from a numeric value. Python input raises EOFError at end of input; this task guarantees the sentinel, so no speculative EOF loop is necessary.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Consume integer lines in [-1000,1000] until the exact line stop, which always occurs. Ignore later input and negative readings; count zero as accepted. Output accepted count and sum, separated by one space.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

Use the exact sentinel comparison you would use in C, not a truth test that discards zero.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, 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