next Becomes continue
Lesson 19 of 48 in Coddy's Python for Ruby Developers course.
Ruby next skips the remaining block or loop iteration; Python uses continue. Both use break to exit a loop, but Ruby break can also supply a result from some iteration expressions, whereas Python break carries no result. Python while checks a condition before each iteration. Update state before a continue when skipping the update would keep the condition true forever. Python has no until statement; invert the condition with not when porting Ruby until. Both languages support += for ordinary counter updates. The task processes input until a sentinel and ignores selected records.
Ruby
n = 0
while n < 3
n += 1
next if n == 2
puts n
endPython
n = 0
while n < 3:
n += 1
if n == 2:
continue
print(n)Porting trap
Do not translate Ruby next as Python next(iterator): that function advances an iterator and does not skip the current loop body.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler