Python's loops also come with a bunch of control statements, which can beused 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 unexpectedsituation. A good example of this is the dreaded "division by zero" error -when dividing one number by another one (which keeps decreasing), it isadvisable to check the divisor and use the "break" statement to exit theloop as soon as it becomes equal to zero. In this case, the "break" statement ensures that the loop is terminatedwhenever an attempt is made to divide by zero. If you'd like to see whathappens without the "break" statement, simply comment out the "if" test inthe code above. continue: The "continue" keyword is used to skip a particular iteration of the loopand move back to the top of the loop - it's demonstrated in the followingexample: 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 thatparticular iteration and go back to the top of the loop. So your string ofnumbers will not include 7 - try it and see for yourself. pass: The "pass" statement essentially means "do nothing". Since Python usesindentation rather than braces to distinguish blocks of code, it generatesa syntax error if it doesn't find an expected code block within a loop orconditional statement. The "pass" statement is used as a placeholder insuch situations. In this case, the "pass" statement is used to avoid an error when theprogram is run (try omitting it and see what happens.) And that's about it for the moment. In this article, you found out a littlemore 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 togenerate 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, afterthat crash course in list objects. In the next article, we'll be continuing our tour of built-in Pythonobjects with a look at dictionaries and tuples, powerful and flexible datastructures 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 ofthe functions built into these objects. See you then!
blog comments powered by Disqus |