8  Iteration and writing functions

So far we have deliberately gotten quite far without two of Python’s most fundamental tools: loops, which repeat an action many times, and functions that we write ourselves to package up and reuse a piece of code. We were able to postpone them because the array and table tools introduced in the earlier chapters let us operate on whole collections of data at once, which removes the need to write a loop in many common situations.

There are still plenty of tasks, though, where writing a loop or your own function is the clearest — or the only — way to get the job done. This chapter introduces both.

8.1 Repeating work with for loops

8.2 Repeating work until a condition is met: while loops

8.3 Writing your own functions

8.4 Summary

8.5 Exercises