Break and Continue

Break and Continue

Two statements change a loop's flow from inside the body.

break ends the loop immediately:

for price in [40, 80, 250, 60]:
    if price > 100:
        print("Too expensive, stopping.")
        break
    print(price)

Output:

40
80
Too expensive, stopping.

The 250 triggered the break; the 60 was never reached.

continue skips the rest of the body and moves to the next pass:

for price in [40, 80, 250, 60]:
    if price > 100:
        continue
    print(price)

Output:

40
80
60

Inside a function, return in a loop body both ends the loop and returns — a common way to express "find the first match":

def first_over(prices, limit):
    for price in prices:
        if price > limit:
            return price
    return None

When no element matches, the loop finishes and the function returns None.

Exercise

  1. Define a function named first_failing with one parameter, scores (a list of numbers).
  2. It returns the first score below 60. If there is none, return None.

first_failing([80, 45, 90, 30]) returns 45.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestFirstFailing(unittest.TestCase):
    def test_returns_the_first_failing_score(self):
        self.assertEqual(first_failing([80, 45, 90, 30]), 45)

    def test_returns_none_when_all_pass(self):
        self.assertIsNone(first_failing([80, 75, 90]))

    def test_returns_none_for_an_empty_list(self):
        self.assertIsNone(first_failing([]))

    def test_exactly_60_is_not_failing(self):
        self.assertIsNone(first_failing([60]))
def first_failing(scores):
    for score in scores:
        if score < 60:
            return score
    return None


print(first_failing([80, 45, 90, 30]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.