Home › Learn › Python › Loops

break and continue

Lesson 13 of 40. Leave a loop early or skip one round.

break ends the loop immediately; the code after the loop runs next. It is how you stop searching once you found the thing. continue skips the rest of the current round and goes straight to the next item.

Both work in for and while loops. A function that searches usually returns from inside the loop instead of breaking, and returns the "not found" value after the loop, because the loop finishing without returning means nothing matched.

for word in ["hi", "stop", "never"]:
    if word == "stop":
        break
    print(word)       # only "hi"

for n in range(5):
    if n % 2 == 0:
        continue
    print(n)          # 1, 3

Your task

Write first_negative(nums) that returns the first number below zero, or None if there is none, and sum_positive(nums) that adds up only the numbers greater than zero, skipping the rest with continue.

Hint 1

for n in nums: if n < 0: return n. After the loop, return None.

Hint 2

Inside sum_positive: if n <= 0: continue, then total += n.

Show the solution
def first_negative(nums):
    for n in nums:
        if n < 0:
            return n
    return None


def sum_positive(nums):
    total = 0
    for n in nums:
        if n <= 0:
            continue
        total += n
    return total

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.