next and continue
Lesson 19 of 48 in Coddy's Python for R Developers course.
R next skips to the next loop iteration; Python continue has that role. Both languages use break to exit the nearest loop. R repeat creates an indefinite loop; Python while True is the usual explicit counterpart. Update loop state before a skip if the update is needed for termination. A Python for loop advances its iterator automatically, while a while loop depends on your own state changes. When consuming records until a sentinel, check the sentinel before parsing it as an integer. Skipping a negative record should not accidentally skip the read that advances to the next record.
R
n <- 0
while (n < 3) {
n <- n + 1
if (n == 2) next
cat(n, "\n", sep="")
}Python
n = 0
while n < 3:
n += 1
if n == 2:
continue
print(n)Porting trap
Python next is an iterator-advancing function, not a spelling of the R loop-control statement.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler