Menu
CoddyTech

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
end

Python

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 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 Ruby Developers

Practice on your own: Online Python compiler