INTRODUCTION |
In a larger picture, you may want to use figures such as triangles and squares repeatedly. However, the turtle itself does not know what a triangle or a square is. Therefore you have to explain to the turtle how to draw the figures each time with a complete program code. Is this possible in an easier way? It is! You can teach the turtle new commands, for example how to draw a square or a triangle. Then you simply have to tell the turtle that it should execute such a command, namely draw a square or a triangle. In order to define a new command, you can choose any given identifier, for example square, and then write def square(): After that, you then write down all of the instructions belonging to the new command. In order for the computer to know what is part of the new command, the instructions must be indented. |
DEFINING YOUR OWN COMMAND |
from gturtle import * def square(): repeat 4: forward(100) left(90) makeTurtle() setPenColor("red") square() right(120) setPenColor("blue") square() right(120) setPenColor("green") square()
|
MEMO |
You can define a new command using def identifier(): Choose a name that reflects the activity of the command. All instructions that belong to the new command must be indented
def identifier():
instuctions
Do not forget to put brackets and the colon after the identifier! In Python you also call new commands functions. When you use the function square() one could also say that the function is "called". We should get used to placing the function definitions in the program header, since they have to be defined before they are called |
EXERCISES |
|