First steps with Python programming
Going Loopy
The solution, as you might already have guessed, is to write a program that repeats the draw and turn instructions as many times as needed. Here it is:
import turtle for g in range(4): turtle.forward(150) turtle.right(90)
The second line in this program tells Python you want to repeat the next bit four times; in fact, it does more than that. It creates a variable (i.e., a place for storing information) and calls it g
. It puts the numbers 0, 1, 2, and 3 into that variable in turn each time the loop repeats.
Look at the colon at the end of the second line. When you press Return after it, the next line is automatically indented for you. The way you tell Python which instructions belong to the for
command is by indentation. The convention is to use four spaces, and the program won't work if you don't use indentation consistently. By forcing you to indent, Python makes sure your programs (and everyone else's) are easy to read.
Parts of a program that repeat are often called loops. The loop is much easier to work with than all those individual drawing commands. If you decide to draw a triangle instead of a square, for example, you can just change the for
command to repeat 3
times, and the angle of the turn to 120
degrees.
A Touch of Color
If you want to change the pen color, you can do so in several different ways. One way is to tell the turtle module how much red, green, and blue to mix into a final color. The maximum amount of blue, with no green or red, would be pure blue, for example, and the maximum amount of red and green with no blue produces yellow.
To make the turtle draw yellow lines, use:
turtle.colormode(255) turtle.pencolor(255, 255, 0)
The first line only needs to be put in your program once to tell the turtle module the format in which you want to specify colors. The second line gives the amount of red, green, and blue (in that order) on a scale from 0 to 255, and you can use it whenever you want to change the pen color – try it out by experimenting with different numbers.
The word "color," you'll notice, is spelled the US way here. It won't work if you slip a "u" into it.
Buy this article as PDF
Pages: 5
(incl. VAT)