The random
Module
For the last few lessons, we have been using the turtle
module. Another module that we will use often in this class is the random
module, a simple Python library that lets us create (pseudo)random numbers.
random.randrange()
randrange()
is a command that functions much like range()
with start and stop parameters, but produces random integers instead. Here’s an example:
import random
for i in range(5):
print(random.randrange(1, 11)) # prints a random integer from 1 to 10
We can also use the step parameter with random.randrange()
:
import random
for i in range(5):
print(random.randrange(1, 11, 2)) # prints a random ODD integer from 1 to 10
random.randint()
randint()
works exactly like random.randrange()
, but the stop value is included as a possible value. So print(random.randrange(1,20))
would print a random integer from 1 to 20.
random.random()
The last command from the random
module is random.random()
, which returns a random float value between 0 and 1. At first, this may seem fairly useless, until you remember that a random decimal between 0 and 1 is equivalent to a random percentage. One very helpful application of to use random.random()
to create random colors.
The turtle
module allows us to set pen colors and fill colors by either entering a color string (like “blue” or “lightgreen”) or by entering an RGB value (red-green-blue). An RGB value is a set of three percentages that correspond to the percentage of red, the percentage of green, and the percentage of blue to use in the selected color. Since random.random()
returns a random percentage in decimal form, we can use it to create a random color:
import random
import turtle
wn = turtle.Screen()
wn.bgcolor(random.random(), random.random(), random.random()) # selects a random background color
bob = turtle.Turtle()
wn.exitonclick()
Exercises:
- Use a
for
loop to print 10 random numbers. - Use a
for
loop to print ten random even numbers between 1 and 1000. 1000 should be a possible answer.