Python 101 (part 3): A Twist In The Tail - Just Passin' Through (
Page 8 of 8 )
Python's loops also come with a bunch of control statements, which can be
used to modify their behaviour. I've listed the important ones below,
together with examples:
break:
The "break" keyword is used to exit a loop when it encounters an unexpected
situation. A good example of this is the dreaded "division by zero" error -
when dividing one number by another one (which keeps decreasing), it is
advisable to check the divisor and use the "break" statement to exit the
loop as soon as it becomes equal to zero.
for x in range(10, -1, -1):
# check for division by zero and exit
if x == 0:
break
print 100 / x
In this case, the "break" statement ensures that the loop is terminated
whenever an attempt is made to divide by zero. If you'd like to see what
happens without the "break" statement, simply comment out the "if" test in
the code above.
continue:
The "continue" keyword is used to skip a particular iteration of the loop
and move back to the top of the loop - it's demonstrated in the following
example:
for x in range(10):
if x == 7:
continue
print x
In this case, Python will print a string of numbers from 1 to 10 - however,
when it hits 7, the "continue" statement will cause it to skip that
particular iteration and go back to the top of the loop. So your string of
numbers will not include 7 - try it and see for yourself.
pass:
The "pass" statement essentially means "do nothing". Since Python uses
indentation rather than braces to distinguish blocks of code, it generates
a syntax error if it doesn't find an expected code block within a loop or
conditional statement. The "pass" statement is used as a placeholder in
such situations.
if var == "neo":
call_neo_func()
elif var == "trinity":
# insert code later
pass
elif var == "agent":
# insert code later
pass
In this case, the "pass" statement is used to avoid an error when the
program is run (try omitting it and see what happens.)
And that's about it for the moment. In this article, you found out a little
more about adding flow control to your Python programs with the "for" and
"while" loops, and you also learnt about the ancillary "break", "continue"
and "pass" statements. You saw how the range() function can be used to
generate number ranges, which can then be used in combination with a "for"
loop. And you now know a little more about Python's data structures, after
that crash course in list objects.
In the next article, we'll be continuing our tour of built-in Python
objects with a look at dictionaries and tuples, powerful and flexible data
structures which let you do weird and wonderful things with your code.
We'll also re-visit numbers, strings and lists for a look at some more of
the functions built into these objects. See you then!