while, break, and continue
Lesson 19 of 48 in Coddy's Python for JavaScript Developers course.
Stop reading at a sentinel and skip unwanted values while guaranteeing that each continuing iteration makes progress.
JavaScript
const values = [3, -1, 4, 0, 9];
let total = 0;
for (const value of values) {
if (value === 0) break;
if (value < 0) continue;
total += value;
}
console.log(total);Python
values = [3, -1, 4, 0, 9]
total = 0
for value in values:
if value == 0:
break
if value < 0:
continue
total += value
print(total)What changes
These programs both print 7. Python break exits the nearest loop, so the trailing 9 is never processed. Python continue skips the remaining statements in the current iteration. A while condition: loop checks its condition before every iteration; it can run zero times. When the number of inputs is unknown, while True: can read a value and use break when an agreed sentinel arrives. The sentinel belongs to the input protocol, not to the ordinary data. Only use an unbounded reading loop when the contract guarantees a stopping value.
Common mistake
With a manually maintained index, placing its increment after a possible continue can trap the loop on the same item. In a reading loop, read the next line at the top so every continued iteration consumes fresh input. Avoid checking general truthiness when only one particular value means stop.
Your task
Process readings until the exact stop word and distinguish skipped readings from the sentinel.
Challenge
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler