Turtle Graphic & Module Flashcards
Turtle module
import turtle # allows us to use the turtles module
win = turtle.Screen() # creates a graphics window
alex = turtle.Turtle() # creates a turtle named alex
alex.forward(150) # tell alex to move forward by 150 pixels
alex.left(90) # turn left by 90 degrees
alex.forward(75) # complete the second side of a rectangle
More turtle option
import turtle
wn = turtle.Screen()
wn.bgcolor(“lightgreen”) # set the window background color
tess = turtle.Turtle()
tess. color(“blue”) # set tess’s color
tess. pensize(3) # set the width of her pen
A herd of turtles
#we can have many turtle at one import turtle wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen")
tess = turtle.Turtle() # Create tess and set some attributes
tess. color(“hotpink”)
tess. pensize(5)
alex = turtle.Turtle() # Create alex
“for” loop
import turtle
# Set up alex wn = turtle.Screen() wn.bgcolor("lightgreen") alex = turtle.Turtle() alex.pensize(5)
Repeat four times to draw a square
for i in [0,1,2,3]:
alex.forward(100)
alex.left(90)
wn.exitonclick()
# Repeat four times & change color for a_color in ["yellow", "red", "purple", "blue"]: alex.color(a_color) alex.forward(100) alex.left(90)
“range” function
for i in rage(1, 20, 2): #range(start, stop, step)
print i
Extra turtle control
color, fillcolor, heading, position, goto, begin_fill, end_fill, stamp, shape, speed.
math module
#contain typical math function import math
print math.pi
print math.e
print math.sqrt(2.0)
print math.sin(math.radians(90)) # sin of 90 degrees
random module
import random
prob = random.random() # return a random floating number in [0.0, 1.0)
print prob
diceThrow = random.randrange(1, 7) # return a random integer in [1, 7)
print diceThrow