Is a break statement required or is the return statement enough?

随声附和 提交于 2020-02-03 10:32:32

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/38675529/is-a-break-statement-required-or-is-the-return-statement-enough

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!