|
1 | 1 | Functions with parameters |
2 | 2 | ************************* |
| 3 | +Introduction |
| 4 | +============ |
3 | 5 |
|
4 | | -Todo |
| 6 | +Now we know how to *factorise* this code a little. But functions as we have defined them so far are not flexible. the variables are defined inside the function, |
| 7 | +and we need to rewrite a whole function to cahnge the value of an angle, or a distance in it. |
| 8 | + |
| 9 | +That is why we need to be able to give parameters, or also called *arguments* so that *names* we use in the function can be used with different values each time we call the function: |
| 10 | + |
| 11 | +Remember how we defined the function ``line_without_moving`` in the previous section:: |
| 12 | + |
| 13 | + def line_without_moving(): |
| 14 | + forward(50) |
| 15 | + backward(50) |
| 16 | + |
| 17 | +We can improve it by giving it a parameter:: |
| 18 | + |
| 19 | + def line_without_moving(length): |
| 20 | + forward(length) |
| 21 | + backward(length) |
| 22 | + |
| 23 | +The parameter acts as a *name* only known inside the function's definition. We use the newly defined function by calling it with the value we want the parameter to have like this:: |
| 24 | + |
| 25 | + line_without_moving(50) |
| 26 | + line_without_moving(40) |
| 27 | + |
| 28 | +We have been using functions with parameters since the beginning of the tutorial with the *forward*, *left*, etc... |
| 29 | + |
| 30 | + |
| 31 | +And we can put as many arguments (or parameters) as we want, separating them with commas and giving them different names:: |
| 32 | + def tilted_line_without_moving(length,angle): |
| 33 | + left(angle) |
| 34 | + forward(length) |
| 35 | + backward(length) |
| 36 | + |
| 37 | + |
| 38 | +A parameterised function for a variable size hexagon |
| 39 | +==================================================== |
| 40 | + |
| 41 | +Exercise |
| 42 | +-------- |
| 43 | +Write a function that takes allows you to draw hexagons of any size you want, each time you call the function. |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +A function of several parameters |
| 48 | +================================ |
| 49 | + |
| 50 | +Exercise |
| 51 | +-------- |
| 52 | + |
| 53 | +Write a function that draws a honeycomb with a variable number of hexagons, of variable sizes |
| 54 | + |
| 55 | + |
| 56 | +Solution |
| 57 | +-------- |
| 58 | + |
| 59 | +:: |
| 60 | + |
| 61 | + def hexagon(size): |
| 62 | + for i in range(6): |
| 63 | + forward(size) |
| 64 | + left(60) |
| 65 | + def honeycomb(size,count): |
| 66 | + for i in range(count): |
| 67 | + hexagon(size) |
| 68 | + forward(size) |
| 69 | + right(60) |
| 70 | + |
0 commit comments