(Jul-25-2018, 09:14 PM)Skaperen Wrote: [ -> ]what will the break statements do without the loop?
Then you'll get a SyntaxError.
You are only allowed to use the
continue
/
break
statement inside loops.
In functions you can use also return, to break out of a loop.
Additionally you have the possibility to use else in
for-loops
. In this case the else block is only executed, if the loop finishes. Today I've written code, which uses this control flow.
def find_and_remove(sequence, **kwargs):
for element in sequence:
if all(element.get(key) == kwargs.get(key) for key in kwargs):
result = element
# break out of the loop
# the else block is not executed in this case.
break
else:
# if the loop finishes, the function returns explicit None
return None
sequence.remove(result)
# the result is only returned, a match was found
return result
Quote:the goal is to define where control ends up at when each if clause with a break reaches that break statement.
If I understood it right, you want to have some branches inside a loop, which decides to break out of this loop. Yes, this is possible and often used. In my example this is used.
Each block in Python has it's own scope (maybe there are corner cases).
When you use a
continue
/
break
statement in nested scopes (eg. nested loops and other scopes),
it bubbles up, until it reaches the loop.
def foo():
for a in range(20):
for b in range(10):
for c in range(5):
with something() as bar:
for line in bar:
if 'foo' in line:
break
# this statement will break the
# for line in bar: loop
If you want to break out of the loop
for b in range(10)
you can solve this also.
This example is not the final solution.
def foo():
for a in range(20):
for b in range(10):
# we want to break out of this loop if a condition is true
for c in range(5):
with something(a, b, c) as bar:
for line in bar:
if 'foo' in line:
break
# this statement will break the
# for line in bar: loop
elif 'bar' in line:
# if this block is executed, we want to break out of the
# loop: for b in range(10)
I guess it's better to refactor this code a little bit. We can use functions to make it easier for us to control the flow and still have an overview what's going on.
def do_something(*args)
with something(*args) as bar:
for line in bar:
if 'foo' in line:
return True
elif 'bar' in line:
return False
def abc_range():
result = True
for a in range(20):
for b in range(10):
if not result:
# this breaks out of the b-loop
break
for c in range(5):
result = do_something(a, b, c)
# now the result is set and we need to break
# out of the c-loop, where the b-loop continues
if not result:
break
I guess with more effort you can avoid deep nested loops with if-branches.
Quote:in other languages, i'd be using a branch instruction or a goto statement to do this.
Using goto in other languages, leads to unreadable code and often in unpredictable code.
In High-Level languages you'll not see any use of goto.