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
BeginnerConsume 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler