In this section, we will talk about when to use iteration (for loops) vs. when to use functions. We will also look at examples where we invoke a function from inside a loop, and where we use iteration inside a function.
Both functions and iteration are ways to avoid typing the same (or very similar) lines of code over and over again. This is important because if you have similar lines of code and you discover a bug in one of them, or decide to make a change, you have to make that change in all of them. Whenever you are writing code, if you find yourself writing the same (or very similar) lines of code over and over again, you can probably simplify your code, either by putting that code into a function, or by putting that code inside a loop.
If the code needs to be repeated (over and over again at the same time) across a range of values that change, you probably need a loop in order to step through that range of values. The values might be a numerical range, the items in a list or the characters in a string. In any of these cases you likely need a loop.
A common pattern is to have a loop that iterates through a set of values (a range of numbers, a list of items or the characters in a string), and for each item in that set, call a function to do something. That looks like this:
Remember that to follow Python conventions, we want to declare functions at the top of the script. Then we can call the functions anywhere else in the program, including inside of loops.
not repeating code - the function is called five times from inside a loop. The function is only four lines of code, but if it was repeated five times, it would be 20 lines of code. The code inside the function doesnβt know the round number. It doesnβt need to.
using the modulo operator (%), in this case to keep the index value between 0 and 3 so we keep cycling between four different turtle stamps in the list
using the random module to get random numbers in a range (in this case random x and y coordinates that arenβt too close to the edges of the turtle canvas)
Here is a modification of the turtle program from above that makes use of a loop inside a function, as well as a loop in the main code that calls the function: