break语句是必需的还是返回语句足够了? [英] Is a break statement required or is the return statement enough?

查看:173
本文介绍了break语句是必需的还是返回语句足够了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Python 3(.5)脚本中,对于循环有一个简单的,看起来像这样:

<
> 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 适合您的需求。


In my Python 3(.5) script I have a simple 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

Now, this works as expected and the loop stops on the first match that is found.
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?

Keeping this question in mind, would it be better off for my code to look 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))
    break

解决方案

return exits a function immediately.

If you are in a loop, that breaks out of the loop and no break is required first.

So no, you are not required to use break if return suits your needs.

这篇关于break语句是必需的还是返回语句足够了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆