3

I have the following python function for checking whether a string is a phone number (I know it can be written simpler with regular expressions...)

def isPhoneNumber(text):
    if len(text) != 12:
        return False
    for i in range(0,3):
        if not text[i].isdecimal():
            return False
    if text[3] != '-':
        return False
    for i in range(4,7):
        if not text[i].isdecimal():
            return False
    if text[7] != '-':
        return False
    for i in range(8,12):
        if not text[i].isdecimal():
            return False
    return True

message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office number.'

for i in range(len(message)):
    chunk = message[i:i+12]
    if isPhoneNumber(chunk):
        print('Phone number found: ' + chunk)

If I were writing this I would put the return True as the first line of the function. What prevents the function from returning True when one of the false conditions are True? Is a return statement an implicit break (eg once one of the False conditions are True the code breaks and doesn't process any future lines)?

brb
  • 1,123
  • 17
  • 40
  • 2
    `return` means to immediately stop execution of this function and return to the calling one (there are exceptions where some cleanup code is done yet) – Michael Butscher Dec 27 '17 at 12:03
  • 4
    Yes, `return` ends any function right there. The one exception to this is that `finally`-blocks will be executed if you return from the `try` or `except`. – user2390182 Dec 27 '17 at 12:04
  • 1
    @schwobaseggl Another exception is for `return` in a `with` block – Michael Butscher Dec 27 '17 at 12:05
  • 1
    @MichaelButscher True, but I have to say that was what I expected from a context manager. Very much unlike my first time debugging the mysterious things that happened when I had a return in both the try and the finally block :D – user2390182 Dec 27 '17 at 12:14
  • @schwobaseggl intriguing. do tell the try and finally weirdness. – ShpielMeister Dec 27 '17 at 12:50

1 Answers1

2

If I were writing this I would put the return True as the first line of the function.

But then the function would return (terminate in others words), ignoring everything below the first line, thus your function would always return true.

return is a keyword that forces the function to terminate at that point, no matter what goes lines of code lie beyond that point.

In other words, once the execution of your function meets a return keyword, it will stop the function from executing further, and return to the calling function.

Read more in Why would you use the return statement in Python?

gsamaras
  • 71,951
  • 46
  • 188
  • 305