Reading Questions
Quiz
Modules
- We already know how to use modules, we’ve been using them since the first Python program you created
- 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) - 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 heightimport graphics graphics.draw_oval(0, 0, 100, 100)
- 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
import graphics graphics.draw_oval(100, 100, 100, 200, 'red', 'blue', 5)
To create an animation, need to draw multiple times
import graphics for i in range(100) graphics.draw_oval(i, i, 100, 100)
- Add a loop to draw multiple ovals, but they all get drawn very quickly
To add a delay, use the
wait
functionimport graphics for i in range(100) graphics.draw_oval(i, i, 100, 100) graphics.wait()
To remove the trail, need to clear the screen
import graphics for i in range(100) graphics.clear() graphics.draw_oval(i, i, 100, 100) graphics.wait()