Randomness notes

posted by: Ms. Martin 1 March 2011 2 Comments

I got a request for more details on what we learned Monday.  Feel free to e-mail me with specific questions, too.

Many interesting programs including most games have some sort of random component to them.  Some examples:

  • In Solitaire, the cards are shuffled randomly.
  • Every time you get hit in a shoot ‘em up game, your damage is randomly generated.
  • In a flash card studying program, cards are selected in a random order.
  • Your passwords are all encrypted using random numbers.

In reality, it’s impossible for a computer to generate a truly random number, so instead we rely on pseudorandom numbers.  Those are good enough for any situation where no money is involved (not for the lottery)!!

The random module

In order to use random numbers in Python, you must import everything from the random module like this:
from random import *

It’s typical to place all import statements at the top of your program.

Random functions

For now we’ll use two random functions: one to generate random integers and another to generate random floats.

random() – generate a random float in the range [0.0, 1.0). In other words, 0.0 can be generated but not 1.0.

randint(<bound1>, <bound2>) - generate a random integer in the range [<bound1>, <bound2> ]. In other words, both of the bounds can be generated as well as any whole number between the two.

You can read more about the random module in the official Python documentation.

Examples

Makes the turtle a random color then draws a line of that color.

from turtle import *
from random import *

color(random(), random(), random()) # make the turtle a random color
forward(100)

Print 30 random numbers between 1 and 100.

from random import *

for i in range(30):
    print(randint(1, 100))
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.67 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>