CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1
1.2 Modules and turtle graphics
Study notes for Modules and turtle graphics in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.
Big ideas
- A module is a file of ready-made code.
import maththenmath.sqrt(2); orfrom math import sqrtto usesqrt(2)directly; orimport random as rto shorten the name. mathhassqrt, floor, ceil, pi, sin, cos;randomhasrandint(a, b)(both ends included),random()(0 up to 1) andchoice(list).- The turtle module draws by moving a pen:
forward(d),backward(d),left(deg),right(deg),penup()/pendown(),goto(x, y),circle(r),color(...),begin_fill()/end_fill(). - The turtle starts at (0, 0) facing east (right); angles turn counter-clockwise for
left. The screen’s y axis points up, unlike most graphics systems. - Events make drawings interactive:
screen.onkey(func, "Up"),screen.onclick(func),screen.ontimer(func, ms), thenscreen.listen()andscreen.mainloop(). You pass the function name, without parentheses.
Code you should know
A filled square with turtle
import turtle
t = turtle.Turtle()
t.color("black", "gold")
t.begin_fill()
for _ in range(4):
t.forward(100)
t.left(90)
t.end_fill()
turtle.done()Output
A gold square appears in the picture pane.
math and random
import math
import random
print(math.sqrt(144), math.pi, math.floor(3.7), math.ceil(3.2))
roll = random.randint(1, 6)
print("You rolled", roll)
print(random.choice(["rock", "paper", "scissors"]))Output
12.0 3.141592653589793 3 4 You rolled 4 paper
Star with a loop
import turtle
t = turtle.Turtle()
t.pensize(3)
t.color("purple")
for _ in range(5):
t.forward(150)
t.right(144)
t.hideturtle()Output
A five-pointed star.
Worked example
A turtle starts at (0, 0) facing east. It runs
forward(50), left(90), forward(30). Where is it and which way does it face?Show the solution
At (50, 30) facing north (up).
forward(50) moves along x, left(90) turns from east to north, and the second move adds 30 to y.Common mistakes
- Writing
screen.onkey(move(), "Up")with parentheses: that callsmoveonce and registers its return value (None). Passmove. - Forgetting
screen.listen(), so key events never arrive. - Calling
math.sqrtafterfrom math import sqrt, orsqrtafter plainimport math. randint(1, 6)includes 6;range(1, 6)does not.
Exam tipOn the exam you may be asked to draw what a turtle program produces or to write a loop that draws a polygon: exterior angle = 360 / sides.
Keep going in Mathub
Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.