Here is a simple function to find the first word in a list that starts with the letter K.
1 2 3 4
def findK(wordlist): for word in wordlist: if word.startswith("K"): return word
The function will end up returning None in case there are no words starting with K. The loop goes through potentially all of the words, but stops immediately when a word starts with K. This is the early return technique.
Now, however, suppose we have two lists, and the same problem, finding the first word starting with K, in each list. The unfortunate thing about early return is that the function ends too soon: it cannot continue more work after returning. Yes, we could arrange for the calling program to use the findK function twice, but there is another way.
1 2 3 4 5 6 7 8 9 10
def findK(wordlist1,wordlist2): for word1 in wordlist1: if word1.startswith("K"): break # now, word1 is due to first list for word2 in wordlist2: if word2.startswith("K"): break # after the loops, work is done return (word1,word2)
In this second findK function, there is no early return. The function always returns in the last line. Each of the loops does something like a "mini return" (but not actually leaving the function). As soon as a word starting with K appears, control jumps out of the loop, on to the next statement. That is what break does.