简体   繁体   中英

Is return an implicit break in python function

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)?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM