← Python lessons

Stopping a Search with return

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A search checks values one at a time until it finds an answer. Inside a function, return stops the search as soon as the answer is known.

Read Parameters & Return and For Loops first.

One match can settle the question

def contains_negative(numbers):    for number in numbers:        if number < 0:            return True    return Falseprint(contains_negative([4, -2, 7]))print(contains_negative([4, 2, 7]))print(contains_negative([]))

It prints True, False and False.

One negative number proves the answer is True, so the function returns at once. A positive number proves nothing yet: a later number might be negative.

return False sits after the loop, lined up with for. It runs only when every number was checked and none matched. An empty list skips the loop and goes straight there.

Return ends this function call

A return inside a loop ends the whole function, not just one pass of the loop. This search prints each number it checks:

def contains_negative(numbers):    for number in numbers:        print("checking", number)        if number < 0:            return True    return Falseprint(contains_negative([4, -2, 7]))

It checks 4 and -2, then returns True. The 7 is never checked.

Return False too early

Putting return False inside the loop is a common bug. The function stops after the first number:

def contains_negative(numbers):    for number in numbers:        if number < 0:            return True        else:            return Falseprint(contains_negative([4, -2, 7]))  # wrong: prints False

4 is not negative, so return False runs before -2 is checked.

Note: Some searches flip the answers. Ask what one value proves. If one value proves False, return False inside the loop and True after it.

See also: break and continue, Tracing Code.

Your turn

Add the two returns: True when a roll is 6, and False after the loop.

🎯 Goal — make it print exactly:
True
False
def has_six(rolls):    for roll in rolls:        if roll == 6:            pass  # replace pass with a return    # add a return after the loopprint(has_six([2, 6, 3]))print(has_six([1, 2, 5]))

Advanced reading