Menu
CoddyTech

Sentinels Without Truth Traps

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

Go uses for for both counting and condition-controlled loops. Python has a separate while statement, plus for for iterables. break exits the nearest loop; continue skips to its next iteration. Advance a manual index before a possible continue to avoid getting stuck. Here zero is deliberately a sentinel; in the exercise the sentinel is the text stop, and zero is valid data.

Go

Go excerpt inside main; imports: fmt. The verification bundle contains the complete program.

// Inside main:
values := []int{3, -1, 0, 9}
total := 0
for _, n := range values {
    if n == 0 { break }
    if n < 0 { continue }
    total += n
}
fmt.Println(total)

Python

values = [3, -1, 0, 9]
total = 0
i = 0
while i < len(values):
    n = values[i]
    i += 1
    if n == 0:
        break
    if n < 0:
        continue
    total += n
print(total)

Porting trap

The sentinel contract determines when to break. Using if not reading on numeric input would incorrectly stop on zero when only the word stop should end the task.

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. Carry over Go sentinel-loop control, but keep the valid numeric zero separate from the stop token.

Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

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

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 Go Developers

Practice on your own: Online Python compiler