First steps with Python programming
Going Random
As an interesting experiment, you can get the computer to choose color numbers at random. To do that, you'll need to use another module called random
by adding import random
at the start of your program; then, to generate a random number, type
random.randint(0,255)
in the shell to see how it works. The first number in the parentheses is the lowest possible number you want, and the second number is the highest. Each time you enter this line, you'll get a random number in that range. If it repeats, it's a coincidence, like throwing a double six.
Now replace your color numbers in the turtle.pencolor()
instruction with the code that generates a random number, like this:
turtle.pencolor(random.randint(0,255), random.randint(0,255), random.randint(0,255))
This instruction will change the pen to a random color each time you use it. Remember that each opening bracket needs a closing bracket of the same type, so if you get an error, check your punctuation first.
Going Ever Loopier
Python allows you to put loops inside loops, so you can create a program that draws lots of squares. For example, in Listing 1, the program brings together everything you've learned in this article to this point: using the turtle
and random
modules, setting up the turtle's color mode, and starting a loop that repeats 72 times.
Listing 1
Loop de Loop
01 import turtle 02 import random 03 turtle.colormode(255) 04 for h in range(72): 05 turtle.pencolor(random.randint(0,255), random.randint(0,255), random.randint(0,255)) 06 for g in range(4): 07 turtle.forward(150) 08 turtle.right(90) 09 turtle.right(5)
The turtle is given a random pen color, and then a square is drawn in a loop that draws four sides, turning 90 degrees after each. Finally, the turtle turns right 5 degrees before drawing the next square. The result is a circular pattern made of overlapping multicolored squares (Figure 6).
The important thing to notice here is that the loop for drawing the square has been indented by a further four spaces so that it belongs to the loop that repeats 72 times. The number 72, by the way, is calculated by taking 360 degrees in a circle and dividing it by 5, the number of degrees to turn between drawing each square.
Buy this article as PDF
Pages: 5
(incl. VAT)