Python has two ways of affecting the flow of the for or while loop inside the block. The
continue statement means that the rest of the code in the block is skipped for this
particular item in the collection, i.e. jump to the next iteration.
values = [10, -5, 3, -1, 7]
total = 0
for v in values:
if v < 0:
continue # skip the rest of the block for this v
total += v
# At the end total is 20
So here the negative items are left out of the sum. An alternative way of writing the
above without the continue statement is to only add the numbers we do want, rather than
skipping those we don’t:
total = 0
for v in values:
if v >= 0:
total += v
# At the end total is 20
It is a matter of taste which style you prefer. Note that either way the variable v at the
end will still be the last value from the list, whether or not it is negative.
The second way of affecting the flow in a for or while block is the break statement. In
contrast to the continue statement, this immediately causes all looping to finish, and
execution is resumed at the next statement after the loop.
total = 0
for v in values:
if v == 3:
break
total += v
# At the end total is 5, v is 3
Here the third item in the list is 3, so at this point the loop terminates and the sum is
only of the first two items in the list. Note that the loop variable, v, never makes it to the
rest of the list, so stays 3 when the loop terminates.
If you have a for loop inside a for loop, then a break in the inner loop only results in a
jump to the end of the inner loop, not the outer one. This can sometimes be a pain but the
alternative choice would in general have been worse.
There is one extra twist with for loops when you have a break statement in the loop.
Often you want to know if you have broken out of the loop, but otherwise execute some
code if you have not, and Python has a special syntax for adding such code. For example,
here we take values for x and test if they are greater than 5 and less than 10. If we find
such a value foundInRange is defined to be True and the loop is stopped immediately with
break. If no value passes the test, then the loop reaches the end and program execution
reaches the else: block where foundInRange is alternatively defined as False.
for x in someList:
if 5 < x < 10: # Is x between 5 and 10?
foundInRange = True
break # Do not test any more
else:
foundInRange = False # Found nothing
print(foundInRange)
Thus this is a second context in which else can occur. Note that the else lines up with
the for. The code in the else block is executed only if the break statement has not been
executed.
Do'stlaringiz bilan baham: