问题
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