Loops - Internal "return" trumping outside loop "return"?

The answer to Strings and Conditionals (Part One) has a simple loop to go through all the letters in a word to determine if a specific letter is in that word. If the letter exist then return True. My confusion comes in the structure.

The code creates a “for” loop followed by an “if” statement. If while looping through the word the letter is uncovered the “if” statement returns True. HOWEVER, once the “for” loop is done there is then ANOTHER RETURN (return False). This False return is outside the “if” statement. Why does the code not always return False? Why does it skip the False return if the “if” statement above it returns True?

def letter_check(word, letter):
for character in word:
if character == letter:
return True
return False <—

Because the if statement precedes the last return. It will only return False if the loop completes and the program pointer moves to the last line.

Thanks, but it looks like the editor did not properly represent the code I was referring to.
The last “return False” line is actually at the same indent level as the “for” statement. So I would assume the “if” statement would run all the way through, in this case return True but then the final “for” loop would end with the return of False. What am I missing?

Is that what your code looks like?

Ha! Yes! that is what I have. Why does the False in the outer For loop not trump the inner True return?

1 Like

Oops!

def letter_check(word, letter):
    for character in word:
        if character == letter:
            return True
    return False

When a letter matches the function is exited with a value of True. Only if the loop completes will the last line be reached.

Ahh. So when a “return” with a boolean is satisfied all loops in the function stop? Is that what we are saying? Thanks for the patience.

1 Like

The loop will complete if there are no matching characters. Once the loop is done, the only line left to execute is the final return statement.

OK. but I am trying to understand at a more macro level than this single problem. Is it a rule that once a return statement is satisfied all loops in the function stop? That does not seem right. Is it a special case with boolean statements?

Yes, exactly. return means exit and hand the return value over to the caller.

By ‘boolean statement’ if you mean a conditional branch (if …:), there is no special case, only whether the condition is satisfied.