← Python lessons

Stopping a Search with return

A search checks candidates until it finds an answer or runs out of candidates. Inside a function, return can stop the search as soon as the answer is known.

Read Parameters & Return, “return is not print”, first.

One match can settle the question

def contains_negative(numbers):
    for number in numbers:
        if number < 0:
            return True
    return False

print(contains_negative([4, -2, 7]))
print(contains_negative([4, 2, 7]))
print(contains_negative([]))

The results are True, False and False.

One negative number proves that the list contains a negative number, so the function can return True immediately. A non-negative number does not prove that the whole list has no negatives: later values may still match.

The final return False belongs after the loop. It runs only when every candidate has been checked without finding a match. An empty list reaches that return without running the loop body.

Return ends this function call

A return inside a loop ends the whole function call, not just that repetition. If another function called this helper, execution resumes in the caller with the returned value.

Some searches reverse the answers: finding evidence may justify an immediate False, while reaching the end justifies True. Ask what one candidate proves before choosing where to return.

Trace the search

Trace contains_negative([4, 2, -1]). Which values are checked, and which return runs? Then explain why returning False after checking only 4 would be incorrect.


Practise this in the free Python course, where every exercise checks your code instantly.