CPSC120B
Fundamentals of Computer Science I
Day 10 Notes
Modules
Cool Computer Science Thing of the Day
Reading Questions
Quiz
Emacs Tip of the Day
Modules
- We already know how to use modules, we’ve been using them since the first day, turtle
- When you add
import turtle
to the top of a file it allows you to use functions that begin with turtle dot something
- It allows you to use code that someone else wrote
- One useful module is the math module, which gives you functions like
math.sin
, math.cos
, math.log
- In addition to functions, modules can have variable you can use
- The math module has
math.pi
so you don’t have create a constant
- Another useful module is the random module, which give you functions to generate pseudo-random numbers
- The
random.random
function gives random numbers in the range [0.0, 1.0) (note that is exclusive of 1.0)
- The
random.randrange
function give random integers in the specified range (note the upper bound is exclusive
- Note the probablity distribution of both random functions is flat
- What if you want to create a floating point number in a range?
Graphics Module
- So far we have created graphical programs using turtle
- But turtle isn’t very good for creating animations
- The underlying graphical system that turtle is built on is difficult to use
- So I created a module to make creating animations easier
- Using module that is not built-in requires an extra step
- Before importing it, you have to put the module’s .py file in the same directory and the .py file that is using it.
- The graphics module’s documentation has a link to the graphics.py file you can use during lab
- To draw an oval use the
draw_oval
function, need to specify the x, y, width, and height
- In turtle we used
exitonclick
function to keep the window open, the graphics module supports mouse interation so clicking doesn’t close the window
- Use the
mainloop
function to keep the winow open
- Note the coordinate system is different than turtle, (0, 0) is in the upper left and positive y is down
- Can also change the outline, fill, and thickness
- To create an animation, need to draw multiple times
- Add a loop to draw multiple ovals, but they all get drawn very quickly
- To add a delay, use the
wait
function
Lab