gpt4 book ai didi

python - 在 python 函数中返回一个隐式中断

转载 作者:行者123 更新时间:2023-11-28 17:10:22 25 4
gpt4 key购买 nike

我有以下python函数来检查一个字符串是否是一个电话号码(我知道它可以用正则表达式写得更简单......)

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)

如果我正在写这个,我会把 return True 作为函数的第一行。当其中一个错误条件为 True 时,是什么阻止函数返回 True? return 语句是否为隐式中断(例如,一旦 False 条件之一为 True,代码中断并且不处理任何后续行)?

最佳答案

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

但是随后该函数将返回(换句话说终止),忽略第一行以下的所有内容,因此您的函数将始终返回 true。

return 是一个关键字,它强制函数在该点终止,无论发生什么代码行超出该点。

换句话说,一旦你的函数执行遇到return关键字,它就会停止函数继续执行,并返回到调用函数。

阅读更多 Why would you use the return statement in Python?

关于python - 在 python 函数中返回一个隐式中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47991833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com