Session Ready
Exercise

Break and next

To finish your lesson on loops, let's return to the concept of break, and the related concept of next. Just like with repeat and while loops, you can break out of a for loop completely by using the break statement. Additionally, if you just want to skip the current iteration, and continue the loop, you can use the next statement. This can be useful if your loop encounters an error, but you don't want it to break everything.

for (value in sequence) {
    if(next_condition) {
        next
    }
    code
    if(breaking_condition) {
        break
    }
}

You don't have to use both break and next at the same time, this simply shows the general structure of using them.

The point of using next at the beginning, before the code runs, is to check for a problem before it happens.

Instructions
100 XP

The apple vector is in your workspace.

  • Print out apple. You have some missing values!
  • Fill in the blanks in the loop to do the following:
    • Check if value is NA. If so, go to the next iteration.
    • Check if value is above 117. If so, break and sell!
    • Else print "Nothing to do here!".