break语句是必需的还是返回语句足够了? [英] Is a break statement required or is the return statement enough?
问题描述
在我的Python 3(.5)脚本中,对于循环有一个简单的 现在,按预期工作,循环停止在找到的第一个匹配项上。 记住这个问题,我的代码看起来像这样会更好: 如果你在循环中, 因此,不需要使用 In my Python 3(.5) script I have a simple Now, this works as expected and the loop stops on the first match that is found. Keeping this question in mind, would it be better off for my code to look like this:
If you are in a loop, that breaks out of the loop and no So no, you are not required to use 这篇关于break语句是必需的还是返回语句足够了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!,看起来像这样:
<
> request =简单字符串
忽略=(
#包含正则表达式忽略
的元组)
for(i,regex)在枚举(忽略):
如果re.search(正则表达式,请求):
打印(发现正则表达式{0}。。格式(i))
返回假
我知道 break
语句是用来在Python中打破循环的。
知道了这个问题: 必须我使用 break
语句打破一个循环,或者可以使用 return
声明而不是?
request =简单字符串
ignore =(
#包含正则表达式忽略
)
(i,regex)枚举(忽略):
如果re.search(regex,request):
print(找到正则表达式{0}。 .format(i))
break
return
立即退出函数。
break break
code> if return
适合您的需求。for
loop, that looks like this:request = "simple string"
ignore = (
# Tuple that contains regex's to ignore
)
for (i, regex) in enumerate(ignore):
if re.search(regex, request):
print("Found regex {0}.".format(i))
return False
I understand that the break
statement is what is used to break loops in Python.
Knowing this lead to the question: Must I use the break
statement to break a loop or could I get away with using the return
statement instead?request = "simple string"
ignore = (
# Tuple that contains regex's to ignore
)
for (i, regex) in enumerate(ignore):
if re.search(regex, request):
print("Found regex {0}.".format(i))
break
return
exits a function immediately.break
is required first.break
if return
suits your needs.