Turtle example
suggest changeThe following is an example of a user-defined function called over and over from an infinite loop.
import turtle, time, random #tell Python we need 3 different modules
turtle.speed(0) #set draw speed to the fastest
turtle.colormode(255) #special colormode
turtle.pensize(4) #size of the lines that will be drawn
def triangle(size): #This is our own function, in the parenthesis is a variable we have defined that will be used in THIS FUNCTION ONLY. This function creates a right triangle
turtle.forward(size) #to begin this function we go forward, the amount to go forward by is the variable size
turtle.right(90) #turn right by 90 degrees
turtle.forward(size) #go forward, again with variable
turtle.right(135) #turn right again
turtle.forward(size * 1.5) #close the triangle. thanks to the Pythagorean theorem we know that this line must be 1.5 times longer than the other two (if they are equal)
while(1): #INFINITE LOOP
turtle.setpos(random.randint(-200, 200), random.randint(-200, 200)) #set the draw point to a random (x,y) position
turtle.pencolor(random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)) #randomize the RGB color
triangle(random.randint(5, 55)) #use our function, because it has only one variable we can simply put a value in the parenthesis. The value that will be sent will be random between 5 - 55, in the end it really just changes how big the triangle is.
turtle.pencolor(random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)) #randomize color again
time is imported and never used. while(1) does not end. The closing side is size * 1.5, but the hypotenuse of two equal legs is size * sqrt(2), about 1.414 * size. After right(90) and right(135), the turtle is also not heading back to its start, so that side does not close the triangle. The sample is left as written. Turtle was not run, because it opens a window.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents