Christmas is approaching and this makes it a great time to write a festive tutorial to help you learn Python. In this tutorial you will learn how to draw a simple Christmas Tree using Python's turtle module. We are going to do this in an efficient way though, using some of Python's tools to avoid having to repeat ourselves.
This tutorial includes both:
— the text which you can read and follow, and
— a video that will allow you to go through the same steps as in the text.
You can use either, or both, depending on your preferred way of learning.
I will assume you are already familiar with Python coding and that you have used the turtle module before. In this tutorial I will use some intermediate level coding too, but I will explain everything that you need to understand so that you can master this tree-making method.
This tutorial uses:
— the turtle module
— function definitions with input parameters
— for loops with two variables in the for loop statement instead of one
Ready to go?
You can start by setting up the scene:
import turtle window = turtle.Screen() window.bgcolor("sky blue") turtle.done()
You have just created and named the Screen() and changed its background colour to sky blue. This seems like an appropriate colour for the sky, as we are going to place this Xmas tree outdoors.
Next, create the Turtle() that will draw the tree:
tree = turtle.Turtle() tree.color("forest green")
Now the fun starts. Our aim in this tutorial is to write tidy and efficient code that is readable. Notice how I called the turtle tree and not t or some other obscure variable name that doesn't tell the person reading the code what this variable does. These are small things which make a huge difference to your code, especially when your code gets longer.
Our Christmas tree will be made up of a number of green triangles drawn in different places and with different sizes that will give us the classic Christmas tree shape.
When we think about writing efficient code, we want to think of what parts of the code are identical, or very similar, so we can avoid repeating code.
Drawing A Tree Segment
So, start by drawing one of the triangular sections of your tree:
tree.setposition(50, -50) tree.setposition(-50, -50) tree.setposition(0, 0)
You have just drawn a triangle by choosing the three vertices of the triangle. Remember that the turtle starts off in the (0, 0) position, where x=0 and y=0. The tree turtle first moves to the bottom right when x=50 and y=-50. Then it goes left to the other end, where x=-50, and finally it goes back to the top vertex where it started at (0, 0) again.
Next, you can fill in this shape by 'sandwiching' the lines you have just written with begin_fill() and end_fill():
tree.begin_fill() tree.setposition(50, -50) tree.setposition(-50, -50) tree.setposition(0, 0) tree.end_fill()
You should also add a penup() whe