Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for R Developers

Practice on your own: Online Python compiler