Turtle in Python
Introduction
Turtle is a module in Python that allows us to bring shapes, figures, and designs to life on a screen. The various functions within the module allow you to systematically draw any sort of figure with help of a “turtle” object which acts like a pen, following the commands given to it in terms of functions like forward(), backward(), and many more which will be discussed in the latter sections.
Functions in Turtle
The table below will give you an idea of basic functions available to kick start your journey in creating various designs
Drawing in Turtle
In order to utilize Turtle and its features we need to import the Turtle library which comes with the Python package and does not require external installation. Any drawing in Turtle requires these 4 basic steps to be followed:
1. Import Turtle module
Code:
2. Create a screen and Turtle object
We require a screen or window on which our figure can be displayed as well as a Turtle object through which we can draw anything of our choice
Code:
3. Commands to draw the require shape
As an example, let us draw a line of 200 pixels
Code
4. Display
Now that we are done, we must inform Python to display the figure which is drawn and this is achieved with the help of the done function
Output:
Exercise
Let us now try to apply the above-taught functions as well as the algorithm to draw in constructing 3 basic shapes – Square, Rectangle, and any polygon
Shape 1: Square
Code:
Output:
Shape 2: Rectangle
Code:
Output:
Shape 3: Polygon
Code:
Output:
Additional Methods in Turtle
1. Undo Changes:
Sometimes, it becomes inevitable that we make mistakes while sketching out the required shapes. However, Turtle provides the undo method to revert to the previous changes made so that you can continue with drawing using turtle object
Syntax:
2. Clearing Screen:
The screen of the Turtle module can be cleared once and for all using the clear method of Python. This will clear the screen but the variables do not change and the turtle remains in the same position. However, if there are more turtles on your screen they will not be cleared unless it is explicitly called for
Syntax:
Conclusion
By the end of this section, you will have a good understanding of the Python turtle graphics module and implement basic figures using the above-taught functions