break, continue, and the loop else
Two keywords give you finer control inside loops.
break stops the loop immediately, even if more items remain. It is perfect for searching: once you find what you want, you leave.
for n in [4, 9, 7, 2]:
if n > 5:
print("found", n)
break # stop at the first match (9)continue skips the rest of the current pass and jumps to the next item. Use it to ignore values you do not care about:
for n in range(1, 6):
if n % 2 == 0:
continue # skip even numbers
print(n) # prints 1, 3, 5Loops also have an optional else block. It runs only if the loop finished without hitting break. This is the clean way to express "I searched everything and found nothing":
target = 8
for n in [4, 9, 7, 2]:
if n == target:
print("found it")
break
else:
print("not found") # runs because no break happenedRead the loop else as "if we never broke out." It pairs naturally with searches and works the same on while loops.
Define a function first_negative(numbers) that returns the first negative number in the list using a for loop and break. If there are no negatives, return the string "none" using the loop's else clause. For example first_negative([3, 1, -2, 5]) is -2.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.